﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Net.Browser;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml;
using System.Windows.Media.Effects;
using System.Threading;
using System.Windows.Threading;
using System.Windows.Browser;
using System.Text.RegularExpressions;
using System.Windows.Media.Imaging;
using System.Windows.Controls.Primitives;
using System.Reflection;
using ImageTools.IO;
using ImageTools.IO.Png;
using ImageTools;
using ImageTools.IO.Jpeg;
using ImageTools.IO.Bmp;
using System.Collections.Generic;

namespace Perm
{
    public partial class MainPage : UserControl
    {
        #region VAR
        //Переменные

//CONFIG start
        const string city = "ekb";
        const bool CONFIG_SAVE_RATING = true; //default: true
        const bool CONFIG_CHECK_IP = false; //default: true
        const bool CONFIG_SAVE_BANNER = true; //default: true
        const bool CONFIG_SECRET_MENU = true; //default: false
        const bool CONFIG_LOAD_ROAD = true; //default: true
        const bool CONFIG_LOAD_GAS = true; //default: true
        const bool CONFIG_LOAD_CARWASH = true; //default: true
//CONFIG end

        double strokePermkray = 12.0;
        const double roadPermkray = 150000;
        double permkrayX = 10433320 + roadPermkray;
        double permkrayY = 6442929 + roadPermkray;
        int p = 1, value = 0, 
            value2 = 0, value3 = 0, 
            value4 = 0, value5 = 0,
            value6 = 0,
            iRoad = 0, iHouse = 0, 
            iRiver = 0, iGreen = 0,
            currentComment = 0,
            currentVote = 0;
        const double nachzoom = 0.02;
        double zoom = 0.0, 
               MAXrait = 1, MINrait = 1, 
               MAXraitGAS = 1, MINraitGAS = 1,
               MAXraitCarwash = 1, MINraitCarwash = 1;

        bool isDragging = false, 
             roadDown = false, GASDown = false, 
             CarwashDown = false,
             LH = false, LL = false,
             loadTrainComplete = false, 
             duringdrag, flagHouse = true, 
             flagKvart = true, flagVote = false;
        
        Point lastmousedownpos, lastmousepos, 
              nach, prov1, prov2;

        //Эффекты и трансформы
        ScaleTransform _tr = new ScaleTransform();
        ScaleTransform _tr1 = new ScaleTransform();
        DropShadowEffect shadow = new DropShadowEffect();
        PixelShader pixelshader = new PixelShader();
        BlurEffect blur = new BlurEffect();

        //Объект для получения Tag содержимого элемента
        object vivod = new object();        

        //Цвета
        SolidColorBrush RED = new SolidColorBrush(Colors.Red);
        SolidColorBrush BLUE = new SolidColorBrush(Colors.Blue);
        SolidColorBrush BLACK = new SolidColorBrush(Colors.Black);
        SolidColorBrush BLACKalpha = new SolidColorBrush(Color.FromArgb(128,0,0,0));
        SolidColorBrush GREY = new SolidColorBrush(Color.FromArgb(255, 120, 120, 140));
        SolidColorBrush WHITE = new SolidColorBrush(Colors.White);
        SolidColorBrush YELLOW = new SolidColorBrush(Colors.Yellow);
        SolidColorBrush GREEN = new SolidColorBrush(Colors.Green);
        SolidColorBrush YELLOWGREEN = new SolidColorBrush(Color.FromArgb(255, 255, 255, 128));
        SolidColorBrush GREEN2 = new SolidColorBrush(Color.FromArgb(255, 00, 168, 00));
        SolidColorBrush mySolidColorBrush = new SolidColorBrush(Color.FromArgb(255, 243, 242, 218));
        SolidColorBrush mySolidColorBrush1 = new SolidColorBrush(Color.FromArgb(255, 225, 175, 140)); 

        //Таймеры
        DispatcherTimer t = new DispatcherTimer();
        DispatcherTimer voteTimer = new DispatcherTimer();
        DispatcherTimer loadTimerRoad = new DispatcherTimer();
        DispatcherTimer loadTimerGAS = new DispatcherTimer();
        DispatcherTimer loadTimerCarwash = new DispatcherTimer();
        DispatcherTimer loadTimerHouse = new DispatcherTimer();
        DispatcherTimer loadTimerColor = new DispatcherTimer();
        DispatcherTimer loadTimerRaiting = new DispatcherTimer();
        DispatcherTimer loadTimerLandscape = new DispatcherTimer();
        DispatcherTimer saveBanner = new DispatcherTimer();

        //Дочерние окна
        messageBox msg = new messageBox();
        Comment comment = new Comment();
        Statistics stats = new Statistics();

        WriteableBitmap wb = new WriteableBitmap(0,0);
        #endregion

        //LayautRoot_Loaded
        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
            zoom = nachzoom;
            switch (city)
            {
                case "perm":
                    {
                        cityText.Text = "Пермь";
                        break;
                    }
                case "ekb":
                    {
                        cityText.Text = "Екатеринбург";
                        break;
                    }
                case "permkray":
                    {
                        cityText.Text = "Пермский край";
                        zoom = nachzoom / 10;
                        HouseVisible.IsEnabled = false;
                        MapVisible.IsEnabled = false;
                        break;
                    }
                default:
                    {
                        break;
                    }
            }
            comment.city = city;
            if (CONFIG_SECRET_MENU) info.Visibility = Visibility.Visible;
            //Скрытие загрузки элементов
            Loader.Visibility = Visibility.Visible;
            main.Visibility = Visibility.Collapsed;
            zoomProcedure(zoom, nach);            
            getIP();            
            getMaxMin();
            getCountVote();
            MM();
            string s = "Из года в год дороги в городе Перми содержатся на деньги налогоплательщиков. Содержатся разными подрядчиками. Иногда хорошо, а иногда и не очень. Настало время определить, кто из них выполняет свою работу качественно, а кто нет. Все в Ваших руках!" + Environment.NewLine + "     Выберите соответствующую вкладку, установите режим голосования - за хорошие дороги (зеленая кнопка) и укажите мышкой на участки дорог, которые, по-вашему, содержатся хорошо (не более 10 участков). Затем смените режим голосования (красная кнопка) и выберете плохие участки. После выбора нажмите кнопку – «отправить». Ваш голос будет учтен." + Environment.NewLine + "     Так же Вы можете проголосовать за понравившуюся или не понравившуюся Вам АЗС.";
            textIntro.Text = s;
            Storyboard1.Begin();
            Storyboard2.Begin();
            Storyboard1.Completed += new EventHandler(Storyboard1_Completed);
        }

        void Storyboard1_Completed(object sender, EventArgs e)
        {
            //gridIntro.Visibility = Visibility.Collapsed;
            //Loader.Visibility = Visibility.Collapsed;
            //main.Visibility = Visibility.Visible;            
        }
        
        #region ТАЙМЕРЫ
        //Таймер Tick

        void loadTimer_Tick(object sender, EventArgs e)
        {

            if (value > 280 & value < 600)
            {
                TextLoadRoad.Foreground = YELLOW;
            }
            if (value >= 600)
            {
                TextLoadRoad.Foreground = RED;
            }
            value += loadTimerRoad.Interval.Duration().Milliseconds;
            progressBar1.Value = value;
            TextLoadRoad.Text = "время загрузки дорог: " + value.ToString() + " ms";            
        }

        void loadTimerGAS_Tick(object sender, EventArgs e)
        {

            if (value2 > 280 & value2 < 600)
            {
                TextLoadGAS.Foreground = YELLOW;
            }
            if (value2 >= 600)
            {
                TextLoadGAS.Foreground = RED;
            }
            value2 += loadTimerGAS.Interval.Duration().Milliseconds;
            progressBar1.Value = value2;
            TextLoadGAS.Text = "время загрузки АЗС: " + value2.ToString() + " ms";            
        }

        void loadTimerHouse_Tick(object sender, EventArgs e)
        {
            if (value3 > 280 & value3 < 600)
            {
                TextLoadHouse.Foreground = YELLOW;
            }
            if (value3 >= 600)
            {
                TextLoadHouse.Foreground = RED;
            }
            value3 += loadTimerHouse.Interval.Duration().Milliseconds;
            progressBar1.Value = value3;
            TextLoadHouse.Text = "время загрузки строений: " + value3.ToString() + " ms";            
        }

        void loadTimerLandscape_Tick(object sender, EventArgs e)
        {
            if (value6 > 280 & value6 < 600)
            {
                TextLoadLandscape.Foreground = YELLOW;
            }
            if (value6 >= 600)
            {
                TextLoadLandscape.Foreground = RED;
            }
            value6 += loadTimerLandscape.Interval.Duration().Milliseconds;
            progressBar1.Value = value6;
            TextLoadLandscape.Text = "время загрузки ландшафта: " + value6.ToString() + " ms"; 
        }

        void loadTimerRaiting_Tick(object sender, EventArgs e)
        {

            if (value4 > 280 & value4 < 600)
            {
                TextLoadRaiting.Foreground = YELLOW;
            }
            if (value4 >= 600)
            {
                TextLoadRaiting.Foreground = RED;
            }
            value4 += loadTimerRaiting.Interval.Duration().Milliseconds;
            progressBar1.Value = value4;
            TextLoadRaiting.Text = "время загрузки рейтинга: " + value4.ToString() + " ms";

        }

        void loadTimerCarwash_Tick(object sender, EventArgs e)
        {
            if (value5 > 280 & value5 < 600)
            {
                TextLoadCarwash.Foreground = YELLOW;
            }
            if (value5 >= 600)
            {
                TextLoadCarwash.Foreground = RED;
            }
            value5 += loadTimerGAS.Interval.Duration().Milliseconds;
            progressBar1.Value = value5;
            TextLoadCarwash.Text = "время загрузки автомоек: " + value5.ToString() + " ms";
        }

        void voteTimer_Tick(object sender, EventArgs e)
        {
            getCountVote();
            if (VOTE.Text != currentVote.ToString())
            {
                VOTE.Text = currentVote.ToString();
                VOTE2.Text = currentVote.ToString();
                VOTE3.Text = currentVote.ToString();
            }
        }

        #endregion

        #region ВЕБ СЕРВИСЫ

        //Дороги
        void LoadRoad(string type)
        {            
            _LoadRoads.LoadRoadsClient proxyLoadRoads = new _LoadRoads.LoadRoadsClient();
            proxyLoadRoads.DoWorkCompleted += new EventHandler<_LoadRoads.DoWorkCompletedEventArgs>(proxyLoadRoads_DoWorkCompleted);
            proxyLoadRoads.DoWorkAsync(city);
            proxyLoadRoads.CloseAsync();
        }        

        //Строения
        void LoadHouse()
        {
            loadTimerHouse.Interval = new TimeSpan(0, 0, 0, 0, 1);
            loadTimerHouse.Tick += new EventHandler(loadTimerHouse_Tick);
            loadTimerHouse.Start();
            progressBar1.Value = 0;
            progressBar1.Maximum = 1280;
            TextLayer.Text = "Загрузка строений";
                        
            _LoadHouses.LoadHousesClient proxyLoadHouses = new _LoadHouses.LoadHousesClient();
            proxyLoadHouses.DoWorkCompleted += new EventHandler<_LoadHouses.DoWorkCompletedEventArgs>(proxyLoadHouses_DoWorkCompleted);
            proxyLoadHouses.DoWorkAsync(city);            
            proxyLoadHouses.CloseAsync();
        }

        //Реки
        void LoadRivers()
        {
            _Rivers.RiversClient proxyRivers = new _Rivers.RiversClient();
            proxyRivers.DoWorkCompleted += new EventHandler<_Rivers.DoWorkCompletedEventArgs>(proxyRivers_DoWorkCompleted);
            proxyRivers.DoWorkAsync(city);
            proxyRivers.CloseAsync();
        }

        //Зелень
        void LoadGreens()
        {
            _Greens.GreensClient proxyGreens = new _Greens.GreensClient();
            proxyGreens.DoWorkCompleted += new EventHandler<_Greens.DoWorkCompletedEventArgs>(proxyGreens_DoWorkCompleted);
            proxyGreens.DoWorkAsync(city);
            proxyGreens.CloseAsync();
        }

        //АЗС
        void GASstation()
        {
            loadTimerGAS.Interval = new TimeSpan(0, 0, 0, 0, 1);
            loadTimerGAS.Tick += new EventHandler(loadTimerGAS_Tick);
            loadTimerGAS.Start();
            progressBar1.Value = 0;
            progressBar1.Maximum = 66;
            TextLayer.Text = "Загрузка АЗС";
            _GASstation.GASstationClient proxyGasstation = new _GASstation.GASstationClient();
            proxyGasstation.DoWorkCompleted += new EventHandler<_GASstation.DoWorkCompletedEventArgs>(proxyGasstation_DoWorkCompleted);
            proxyGasstation.DoWorkAsync(city);
            proxyGasstation.CloseAsync();
        }

        //Автомойки
        void Carwash()
        {
            loadTimerCarwash.Interval = new TimeSpan(0, 0, 0, 0, 1);
            loadTimerCarwash.Tick += new EventHandler(loadTimerCarwash_Tick);
            loadTimerCarwash.Start();
            progressBar1.Value = 0;
            progressBar1.Maximum = 66;
            TextLayer.Text = "Загрузка автомоек";
            _CarWash.CarWashClient proxyCarWash = new _CarWash.CarWashClient();
            proxyCarWash.DoWorkCompleted += new EventHandler<_CarWash.DoWorkCompletedEventArgs>(proxyCarWash_DoWorkCompleted);
            proxyCarWash.DoWorkAsync(city);
            proxyCarWash.CloseAsync();
        }
        
        //TOP (Подрядчики)
        void MM()
        {
            _MM.MMClient proxyMM = new _MM.MMClient();
            proxyMM.DoWorkCompleted += new EventHandler<_MM.DoWorkCompletedEventArgs>(proxyMM_DoWorkCompleted);
            proxyMM.DoWorkAsync(city);
            proxyMM.CloseAsync();
        }        

        //Проверка голосования по IP
        void CheckVote(string IP)
        {
            _CheckVote.CheckVoteClient proxyCheckVote = new _CheckVote.CheckVoteClient();
            proxyCheckVote.DoWorkCompleted += new EventHandler<_CheckVote.DoWorkCompletedEventArgs>(proxyCheckVote_DoWorkCompleted);
            proxyCheckVote.DoWorkAsync(city, IP);
            proxyCheckVote.CloseAsync();
        }

        //Получения Максимального и минимального рейтинга и количества голосов
        private void getMaxMin()
        {
            loadTimerRaiting.Interval = new TimeSpan(0, 0, 0, 0, 1);
            loadTimerRaiting.Tick += new EventHandler(loadTimerRaiting_Tick);
            loadTimerRaiting.Start();
            progressBar1.Value = 0;
            progressBar1.Maximum = 86;
            TextLayer.Text = "Обновление рейтинга";
            _RaitingMaxMin.RaitingMaxMinClient proxyMaxMin = new _RaitingMaxMin.RaitingMaxMinClient();
            proxyMaxMin.DoWorkCompleted += new EventHandler<_RaitingMaxMin.DoWorkCompletedEventArgs>(proxyMaaxMin_DoWorkCompleted);
            proxyMaxMin.DoWorkAsync(city);
            proxyMaxMin.CloseAsync();
        }

        //Сохранение рейтинга
        private void ЗаписьРейтинга(string badRoad, string goodRoad, string badGas, string goodGas, string badCarwash, string goodCarwash)
        {
            _SaveReiting.SaveReitingClient proxySaveReiting = new _SaveReiting.SaveReitingClient();
            proxySaveReiting.DoWorkCompleted += new EventHandler<_SaveReiting.DoWorkCompletedEventArgs>(proxySaveReiting_DoWorkCompleted);
            proxySaveReiting.DoWorkAsync(city,IP.Text.Split(' ')[1], badRoad, goodRoad, badGas, goodGas, badCarwash, goodCarwash);
            proxySaveReiting.CloseAsync();
        }

        //Получение количества комментариев
        void getCountCom(int id)
        {
            _getCountComments.getCountCommentsClient proxygetCountComments = new _getCountComments.getCountCommentsClient();
            proxygetCountComments.DoWorkCompleted += new EventHandler<_getCountComments.DoWorkCompletedEventArgs>(proxygetCountComments_DoWorkCompleted);
            proxygetCountComments.DoWorkAsync(city, id);
            proxygetCountComments.CloseAsync();
        }        

        //Получение количества голосов
        void getCountVote()
        {
            _getCountVote.getCountVoteClient proxygetCountVote = new _getCountVote.getCountVoteClient();
            proxygetCountVote.DoWorkCompleted += new EventHandler<_getCountVote.DoWorkCompletedEventArgs>(proxygetCountVote_DoWorkCompleted);
            proxygetCountVote.DoWorkAsync(city);
            proxygetCountVote.CloseAsync();
        }
        
#endregion
        
        #region АЗС (ЗАГРУЗКА)
        void proxyGasstation_DoWorkCompleted(object sender, _GASstation.DoWorkCompletedEventArgs e)
        {
            ObservableCollection<_GASstation.GASstationGAS> GASstationList = e.Result;

            int i = 0;
            while (i<GASstationList.Count)
            {
                int id = GASstationList[i].no;
                int reit = GASstationList[i].reit;
                System.Windows.Controls.Image gasimage = new System.Windows.Controls.Image();
                gasimage.Name = "GAS-image-" + id.ToString() + "-";
                gasimage.Source = new BitmapImage(new Uri("../Images/gas2.png", UriKind.RelativeOrAbsolute));
                gasimage.Width = 50;
                gasimage.Height = 50;
                gasimage.IsHitTestVisible = true;
                gasimage.Cursor = Cursors.Hand;
                gasimage.Tag = GASstationList[i];
                Canvas.SetTop(gasimage, -GASstationList[i].Y - gasimage.Height/2);
                Canvas.SetLeft(gasimage, GASstationList[i].X - gasimage.Width/2);

                gasimage.MouseEnter += new MouseEventHandler(gasimage_MouseEnter);
                gasimage.MouseLeftButtonDown += new MouseButtonEventHandler(gasimage_MouseLeftButtonDown);
                gasimage.MouseLeftButtonUp += new MouseButtonEventHandler(gasimage_MouseLeftButtonUp);

                Station.Children.Add(gasimage);

                Border b = new Border();
                if (reit != 0)
                {                    
                    b.Width = gasimage.ActualWidth + 10;
                    b.Height = gasimage.ActualHeight + 10;
                    b.Name = "GAS-" + id.ToString();
                    b.IsHitTestVisible = false;
                    b.CornerRadius = new CornerRadius(10);
                    Canvas.SetTop(b, -GASstationList[i].Y - b.Height / 2);
                    Canvas.SetLeft(b, GASstationList[i].X - b.Width / 2);
                }
                Colored(b, reit);
                i++;
            }
            loadTimerGAS.Stop();
            progressBar1.Value = progressBar1.Maximum;
            TextLayer.Text = "Загрузка АЗС завершена";

            if (CONFIG_LOAD_CARWASH) Carwash();            
        }

        #endregion
        #region ОБРАБОТЧИКИ (АЗС)
        //Обработчики - АЗС
        void gasimage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            GASDown = true;
        }        

        void  gasimage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (GASDown)
                {
                    System.Windows.Controls.Image GAS = (System.Windows.Controls.Image)e.OriginalSource;
                    Status(GAS);
                    GASDown = false;
                }
        }
        
        void gasimage_MouseEnter(object sender, MouseEventArgs e)
        {
            if (tabControl1.SelectedIndex == 1)
            {
                System.Windows.Controls.Image station = (System.Windows.Controls.Image)e.OriginalSource;
                Point p = e.GetPosition(null);
                Perm._GASstation.GASstationGAS info = station.Tag as Perm._GASstation.GASstationGAS;
                popupText1.Text = info.name;
                popupText2.Text = "Адрес: " + info.adress;
                if (info.reit > 0)
                {
                    popupText3.Foreground = new SolidColorBrush(Color.FromArgb(255, 80, 255, 80));
                }
                else if (info.reit < 0)
                {
                    popupText3.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 80, 80));
                }
                else
                {
                    popupText3.Foreground = WHITE;
                }
                popupText3.Text = "Рейтинг АЗС: " + info.reit;
                popupText4.Text = "Комментарии";
                popupText4.MouseLeftButtonUp += new MouseButtonEventHandler(popupText4_MouseLeftButtonUp);
                popup.HorizontalOffset = p.X + 20;
                popup.VerticalOffset = p.Y + 10;
                popup.IsOpen = true;
                Animation(popupGrid, "Grid", "BlurEffect", 0.5, 30, 0);

                text5.Text = "Имя: " + info.name + "ИД: " + info.no;
                comment.commentId = info.no;
                comment.gasOrg = info.name;
                comment.gasAdress = info.adress;
                comment.gasReit = info.reit;
            }
        }        

        void popupText4_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            comment.Show();
        }
        #endregion

        #region АВТОМОЙКИ (ЗАГРУЗКА)
        void proxyCarWash_DoWorkCompleted(object sender, _CarWash.DoWorkCompletedEventArgs e)
        {
            ObservableCollection<_CarWash.CarWashCarwash> CarwashList = e.Result;

            int i = 0;
            while (i < CarwashList.Count)
            {
                int id = CarwashList[i].no;
                int reit = CarwashList[i].reit;
                System.Windows.Controls.Image Carwashimage = new System.Windows.Controls.Image();
                Carwashimage.Name = "Carwash-image-" + id.ToString() + "-";
                Carwashimage.Source = new BitmapImage(new Uri("../Images/carwash2.png", UriKind.RelativeOrAbsolute));
                Carwashimage.Width = 50;
                Carwashimage.Height = 50;
                Carwashimage.IsHitTestVisible = true;
                Carwashimage.Cursor = Cursors.Hand;
                Carwashimage.Tag = CarwashList[i];
                Canvas.SetTop(Carwashimage, -CarwashList[i].Y - Carwashimage.Height / 2);
                Canvas.SetLeft(Carwashimage, CarwashList[i].X - Carwashimage.Width / 2);

                Carwashimage.MouseEnter += new MouseEventHandler(Carwashimage_MouseEnter);
                Carwashimage.MouseLeftButtonDown += new MouseButtonEventHandler(Carwashimage_MouseLeftButtonDown);
                Carwashimage.MouseLeftButtonUp += new MouseButtonEventHandler(Carwashimage_MouseLeftButtonUp);

                canvasCarwash.Children.Add(Carwashimage);

                Border b = new Border();
                if (reit != 0)
                {
                    b.Width = Carwashimage.ActualWidth + 10;
                    b.Height = Carwashimage.ActualHeight + 10;
                    b.Name = "Carwash-" + id.ToString();
                    b.IsHitTestVisible = false;
                    b.CornerRadius = new CornerRadius(10);
                    Canvas.SetTop(b, -CarwashList[i].Y - b.Height / 2);
                    Canvas.SetLeft(b, CarwashList[i].X - b.Width / 2);
                }
                Colored(b, reit);
                i++;
            }
            loadTimerCarwash.Stop();
            progressBar1.Value = progressBar1.Maximum;
            TextLayer.Text = "Загрузка автомоек завершена";

            loadTimerRoad.Interval = new TimeSpan(0, 0, 0, 0, 1);
            loadTimerRoad.Tick += new EventHandler(loadTimer_Tick);
            loadTimerRoad.Start();
            progressBar1.Value = 0;
            progressBar1.Maximum = 600;
            TextLayer.Text = "Загрузка дорог";            
            if (CONFIG_LOAD_ROAD) LoadRoad("auto");
        }
        #endregion
        #region ОБРАБОТЧИКИ (АВТОМОЙКИ)
        //Обработчики - Автомойки
        void Carwashimage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            CarwashDown = true;
        }

        void Carwashimage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (CarwashDown)
            {
                System.Windows.Controls.Image Carwash = (System.Windows.Controls.Image)e.OriginalSource;
                Status(Carwash);
                CarwashDown = false;
            }
        }

        void Carwashimage_MouseEnter(object sender, MouseEventArgs e)
        {
            if (tabControl1.SelectedIndex == 2)
            {
                System.Windows.Controls.Image carwash = (System.Windows.Controls.Image)e.OriginalSource;
                Point p = e.GetPosition(null);
                Perm._CarWash.CarWashCarwash info = carwash.Tag as Perm._CarWash.CarWashCarwash;
                popupText1.Text = info.name;
                popupText2.Text = "Адрес: " + info.adress;
                if (info.reit > 0)
                {
                    popupText3.Foreground = new SolidColorBrush(Color.FromArgb(255, 80, 255, 80));
                }
                else if (info.reit < 0)
                {
                    popupText3.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 80, 80));
                }
                else
                {
                    popupText3.Foreground = WHITE;
                }
                popupText3.Text = "Рейтинг автомойки: " + info.reit;
                popupText4.Text = "Комментарии";
                popupText4.MouseLeftButtonUp += new MouseButtonEventHandler(popupText4_MouseLeftButtonUp);
                popup.HorizontalOffset = p.X + 20;
                popup.VerticalOffset = p.Y + 10;
                popup.IsOpen = true;
                Animation(popupGrid, "Grid", "BlurEffect", 0.5, 30, 0);

                text5.Text = "Имя: " + info.name + "ИД: " + info.no;
                comment.commentId = info.no;
                comment.сarwashOrg = info.name;
                comment.сarwashAdress = info.adress;
                comment.сarwashReit = info.reit;
            }
        }
       
        #endregion

        /// <summary>
        /// Получить тип выводимой дороги по колонке "TSYSTEM" в базе.
        /// </summary>
        /// <param name="tsystem">Транспортная система.</param>
        /// <returns>Тип транспортной системы. (gd - ж/д, air - воздушный, metro - метро, whater - речной, walk - пешеходный, default - остальной)</returns>
        List<string> determine(string tsystem)
        {
            List<string> RETURN = new List<string>();
            if (tsystem == "") { RETURN.Add("default"); return RETURN; }

            string[] air = { "Samolet" };
            string[] metro = { "Metro", "Tramvay", "Tr" };
            string[] whater = { "Retchnoi" };
            string[] walk = { "Pesch", "Pesh", "pesh" };
            string[] gd = { "El", "Poesd", "Poezd", "GD" };
            string[] def = { "LA", "Trolleybus", "Marshrutka", "Bus", "Tb", "Avt" };

            bool airCol = false, metroCol = false, whaterCol = false, walkCol = false, gdCol = false, defCol = false;

            for (int i = 0; i <= walk.Length - 1; i++)
            {
                if (tsystem.Contains(walk[i])) walkCol = true;
            }
            for (int i = 0; i <= air.Length - 1; i++)
            {
                if (tsystem.Contains(air[i])) airCol = true;
            }
            //for (int i = 0; i <= metro.Length - 1; i++)
            //{
            //   if (tsystem.Contains(metro[i])) metroCol = true;
            //}
            for (int i = 0; i <= whater.Length - 1; i++)
            {
                if (tsystem.Contains(whater[i])) whaterCol = true;
            }
            for (int i = 0; i <= gd.Length - 1; i++)
            {
                if (tsystem.Contains(gd[i])) gdCol = true;
            }
            for (int i = 0; i <= def.Length - 1; i++)
            {
                if (tsystem.Contains(def[i])) defCol = true;
            }
            if (defCol) RETURN.Add("default");
            if (gdCol) RETURN.Add("gd");
            if (walkCol) RETURN.Add("walk");
            if (airCol) RETURN.Add("air");
            if (whaterCol) RETURN.Add("whater");
            //if (metroCol) RETURN.Add("default");
            if (RETURN.Count == 0) RETURN.Add("default");
            return RETURN;
        }

        /// <summary>
        /// Определение угла поворота названия улицы.
        /// </summary>
        /// <param name="startX"></param>
        /// <param name="startY"></param>
        /// <param name="endX"></param>
        /// <param name="endY"></param>
        /// <returns></returns>
        double angle(double startX, double startY, double endX, double endY)
        {
            double lengthRoad = Math.Sqrt(Math.Pow((endX - startX), 2) + Math.Pow((endY - startY), 2));

            double katetStartX = endX;
            double katetStartY = endY;
            double katetEndX = endX;
            double katetEndY = startY;

            double lengthKatet = katetEndY - katetStartY;

            double Angle = 0.0;

            int ang = 0;
            if ((endX - startX) > 0)
                ang = -1;
            else ang = 1;
            Angle = (lengthKatet == 0.0) ? 0 : Math.Asin(lengthKatet / lengthRoad) * 180 / Math.PI * ang;

            return Angle;
        }

        #region ДОРОГИ (ЗАГРУЗКА)
        //Дороги
        void proxyLoadRoads_DoWorkCompleted(object sender, _LoadRoads.DoWorkCompletedEventArgs e)
        {            
            ObservableCollection<_LoadRoads.LoadRoadsRoad> getRoad = e.Result;            

            for (iRoad = 0; iRoad <= getRoad.Count - 1; iRoad++)
            {                
                Polyline Road = new Polyline();
                PointCollection Road_Pointcol = new PointCollection();
                Point Road_Pointcol_Point = new Point();

                Polyline Road_addon = new Polyline();
                PointCollection Road_addon_Pointcol = new PointCollection();

                Polyline Road_addon2 = new Polyline();
                PointCollection Road_addon2_Pointcol = new PointCollection();
                                
                Polyline Road_Raiting = new Polyline();
                PointCollection Road_Raiting_Pointcol = new PointCollection();


                TextBlock Street = new TextBlock();

                int id = getRoad[iRoad].id;
                string name = (getRoad[iRoad].name != null) ? getRoad[iRoad].name : "";
                int reit = getRoad[iRoad].reit;
                string tsystem = getRoad[iRoad].tsystem;

                string[] X = getRoad[iRoad].X.Split(';');
                string[] Y = getRoad[iRoad].Y.Split(';');

                for (int j = 0; j <= X.Length - 1; j++)
                {
                    //Заполнение поинколлекции дорожной полилинии.
                    Road_Pointcol_Point.X = (city != "permkray") ? double.Parse(X[j]) : double.Parse(X[j]) - permkrayX;
                    Road_Pointcol_Point.Y = (city != "permkray") ? -double.Parse(Y[j]) : -double.Parse(Y[j]) + permkrayY;
                    Road_Pointcol.Add(Road_Pointcol_Point);
                    Road.Points = Road_Pointcol;

                    //Заполнение поинтколлекции рейтинговой полилинии.
                    if (reit != 0)
                    {
                        Road_Raiting_Pointcol.Add((Point)Road_Pointcol_Point);
                        Road_Raiting.Points = Road_Raiting_Pointcol;
                    }                    
                }
                Road.Name = "Road-" + id.ToString() + "-";
                Road.Tag = getRoad[iRoad];
                Road.IsHitTestVisible = true;
                List<string> typeRoad = determine(tsystem);

                for (int i = 0; i <= typeRoad.Count - 1; i++)
                {
                    if (typeRoad[i] != "default" || typeRoad[i] == "gd")
                    {
                        Road_addon = new Polyline();
                        Road_addon_Pointcol = new PointCollection();
                    }
                    switch (typeRoad[i])
                    {
                        case "gd":
                            {
                                if (typeRoad[0] != "default")
                                {
                                    Road.StrokeThickness = (city != "permkray") ? 32 : 32 * strokePermkray;
                                    Road.Stroke = BLACK;
                                    Road.IsHitTestVisible = false;
                                    Roads.Children.Add(Road);
                                }

                                Road_addon.StrokeThickness = (city != "permkray") ? 16 : 16 * strokePermkray;
                                Road_addon.Stroke = WHITE;
                                DoubleCollection dc = new DoubleCollection();
                                dc.Add(5.0);
                                dc.Add(5.0);
                                Road_addon.StrokeDashArray = dc;
                                Road_addon.StrokeLineJoin = PenLineJoin.Round;
                                Road_addon_Pointcol = Clone(Road_Pointcol);
                                Road_addon.Points = Road_addon_Pointcol;
                                Roads.Children.Add(Road_addon);
                                break;
                            }
                        case "metro":
                            {
                                if (typeRoad[0] == "metro")
                                {
                                    Road.StrokeThickness = (city != "permkray") ? 16 : 16 * strokePermkray;
                                    Road.Stroke = GREY;
                                    Road.Cursor = Cursors.Hand;
                                    Roads.Children.Add(Road);
                                }

                                Road_addon.StrokeThickness = (city != "permkray") ? 8 : 8 * strokePermkray;
                                Road_addon.Stroke = YELLOW;
                                DoubleCollection dc = new DoubleCollection();
                                dc.Add(3.0);
                                dc.Add(3.0);
                                Road_addon.StrokeDashArray = dc;
                                Road_addon.StrokeLineJoin = PenLineJoin.Round;
                                Road_addon_Pointcol = Clone(Road_Pointcol);
                                Road_addon.Points = Road_addon_Pointcol;
                                Roads.Children.Add(Road_addon);
                                break;
                            }
                        case "air":
                            {
                                Road.StrokeThickness = (city != "permkray") ? 32 : 32 * strokePermkray;
                                Road.Stroke = RED;
                                DoubleCollection dc = new DoubleCollection();
                                dc.Add(10.0);
                                dc.Add(5.0);
                                Road.StrokeDashArray = dc;
                                Road.StrokeLineJoin = PenLineJoin.Round;
                                Road.IsHitTestVisible = false;
                                Roads.Children.Add(Road);
                                break;
                            }
                        case "whater":
                            {
                                Road.StrokeThickness = (city != "permkray") ? 12 : 12 * strokePermkray;
                                Road.Stroke = BLUE;
                                DoubleCollection dc = new DoubleCollection();
                                dc.Add(2.0);
                                dc.Add(2.0);
                                Road.StrokeDashArray = dc;
                                Road.StrokeLineJoin = PenLineJoin.Round;
                                Roads.Children.Add(Road);
                                break;
                            }
                        case "walk":
                            {
                                if (i == 0)
                                {
                                    Road.StrokeThickness = (city != "permkray") ? 16 : 16 * strokePermkray;
                                    Road.Stroke = GREY;
                                    Road.Cursor = Cursors.Hand;
                                    Roads.Children.Add(Road);

                                    Road_addon.StrokeThickness = (city != "permkray") ? 5 : 5 * strokePermkray;
                                    Road_addon.Stroke = YELLOW;
                                    Road.Cursor = Cursors.Hand;
                                    DoubleCollection dc = new DoubleCollection();
                                    dc.Add(1.0);
                                    dc.Add(1.0);
                                    Road_addon.StrokeDashArray = dc;
                                    Road_addon.StrokeLineJoin = PenLineJoin.Round;
                                    Road_addon_Pointcol = Clone(Road_Pointcol);
                                    Road_addon.Points = Road_addon_Pointcol;
                                    Roads.Children.Add(Road_addon);
                                }
                                break;
                            }
                        default:
                            {
                                Road.StrokeThickness = (city != "permkray") ? 16 : 16 * strokePermkray;
                                Road.Stroke = GREY;
                                Road.Cursor = Cursors.Hand;
                                Roads.Children.Add(Road);
                                break; 
                            }
                    }
                }
                
//TAG rating
                Road_Raiting.Tag = getRoad[iRoad];
                Road_Raiting.IsHitTestVisible = true;

                Road.StrokeEndLineCap = PenLineCap.Round;
                Road.StrokeStartLineCap = PenLineCap.Round;
                Road.StrokeLineJoin = PenLineJoin.Round;
                
                if (reit != 0)
                {
                    Road_Raiting.Name = "Rait-" + id.ToString();
                    Road_Raiting.StrokeThickness = (city != "permkray") ? 32 : 32 * strokePermkray;
                    Road_Raiting.StrokeEndLineCap = PenLineCap.Round;
                    Road_Raiting.StrokeStartLineCap = PenLineCap.Round;
                    Road_Raiting.StrokeLineJoin = PenLineJoin.Round;
                }               

                #region Подписи улиц
                //Подписи улиц
                if (name != "")
                {
                    double startX = (city != "permkray") ? double.Parse(X[0]) : double.Parse(X[0]) - permkrayX;
                    double startY = (city != "permkray") ? -double.Parse(Y[0]) : -double.Parse(Y[0]) + permkrayY;

                    double endX = (city != "permkray") ? double.Parse(X[X.Length - 1]) : double.Parse(X[X.Length - 1]) - permkrayX;
                    double endY = (city != "permkray") ? -double.Parse(Y[Y.Length - 1]) : -double.Parse(Y[Y.Length - 1]) + permkrayY;

                    //Получаем угол поворота названия улицы, относительно отрезка дороги.
                    double Angle = angle(startX, startY, endX, endY);
                    RotateTransform rotate = new RotateTransform();
                    rotate.CenterX = 0;
                    rotate.CenterY = Street.ActualHeight / 2;
                    rotate.Angle = Angle;
                    Street.RenderTransform = rotate;

                    //Вывод названия улицы.
                    Street.Name = "Street-" + id.ToString();
                    Street.FontSize = (city != "permkray") ? 9 : 9 * strokePermkray;
                    Street.Foreground = WHITE;
                    Street.IsHitTestVisible = false;

                    double StreetX = ((startX + endX) / 2) + 2.5;
                    double StreetY = ((startY + endY) / 2) - 9.5;

                    Canvas.SetLeft(Street, StreetX);
                    Canvas.SetTop(Street, StreetY);

                    Street.Text = name;// +"Угол:" + Math.Round(Angle, 2) + " X1:" + startX + " X2:" + endX + " Y1:" + startY + " Y2:" + endY;

                    if (iRoad != 0)
                    {
                        if (getRoad[iRoad].name != getRoad[iRoad - 1].name)
                        {
                            Streets.Children.Add(Street);
                        }
                    }
                    //Окраска рейтинга 
                    Colored(Road_Raiting, reit);
                }
                #endregion
                
                Road.MouseEnter += new MouseEventHandler(Road_MouseEnter);
                Road.MouseLeftButtonDown += new MouseButtonEventHandler(Road_MouseLeftButtonDown);
                Road.MouseLeftButtonUp += new MouseButtonEventHandler(Road_MouseLeftButtonUp);
                Road_Raiting.MouseEnter += new MouseEventHandler(Road_Raiting_MouseEnter);
            }
            switch (city)
            {
                case "perm":
                    {
                        MyTranslate.X = LayoutRoot.ActualWidth / 2;
                        MyTranslate.Y = LayoutRoot.ActualHeight / 2;
                        break;
                    }
                case "ekb":
                    {
                        MyTranslate.X = -(76484 / LayoutRoot.ActualHeight * 2);
                        MyTranslate.Y = LayoutRoot.ActualWidth - (72992 / LayoutRoot.ActualWidth * 2);
                        break;
                    }
                case "permkray":
                    {
                        
                        MyTranslate.Y = LayoutRoot.ActualHeight/2;
                        MyTranslate.X = LayoutRoot.ActualWidth/2;
                        break;
                    }
            }           
            nach.X = MyTranslate.X;
            nach.Y = MyTranslate.Y;
            
            loadTimerRoad.Stop();
            progressBar1.Value = progressBar1.Maximum;
            TextLayer.Text = "Загрузка дорог завершена";
            Continue.Visibility = Visibility.Visible;            
        }

        void Road_Raiting_MouseEnter(object sender, MouseEventArgs e)
        {
            Polyline ROAD = (Polyline)e.OriginalSource;
            Point p = e.GetPosition(null);
            Perm._LoadRoads.LoadRoadsRoad info = ROAD.Tag as Perm._LoadRoads.LoadRoadsRoad;
            if (info.name != "")
            {
                popupText2.Text = "Улица: " + info.name;
            }
            else
            {
                popupText2.Text = "Перегон №" + info.id;
            }
            if (info.contractor != "")
            {
                popupText1.Text = "Подрядчик: " + info.contractor;
            }
            else
            {
                popupText1.Text = "Подрядчик: нет информации";
            }
        }
        
        #endregion        
        #region ОБРАБОТЧИКИ (ДОРОГИ)
//Обработчики - Дороги

        void Road_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            roadDown = true;
        }

        void Road_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (roadDown)
                {
                    Polyline ROAD = (Polyline)e.OriginalSource;
                    Status(ROAD);
                    roadDown = false;
                }
        }

        void Road_MouseEnter(object sender, MouseEventArgs e)
        {
            if (tabControl1.SelectedIndex == 0)
            {
                Polyline ROAD = (Polyline)e.OriginalSource;
                Point p = e.GetPosition(null);
                Perm._LoadRoads.LoadRoadsRoad info = ROAD.Tag as Perm._LoadRoads.LoadRoadsRoad;
                if (info.name != "")
                {
                    popupText2.Text = "Улица: " + info.name;
                }
                else
                {
                    popupText2.Text = "Перегон №" + info.id;
                }
                if (info.contractor != "")
                {
                    popupText1.Text = "Подрядчик: " + info.contractor;
                }
                else
                {
                    popupText1.Text = "Подрядчик: нет информации";
                }

                if (info.reit > 0)
                {
                    popupText3.Foreground = new SolidColorBrush(Color.FromArgb(255, 80, 255, 80));
                }
                else if (info.reit < 0)
                {
                    popupText3.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 80, 80));
                }
                else
                {
                    popupText3.Foreground = WHITE;
                }
                getCountCom(info.id);
                popupText3.Text = "Рейтинг дороги: " + info.reit;
                popupText4.MouseLeftButtonUp += new MouseButtonEventHandler(popupText4_MouseLeftButtonUp);
                popup.HorizontalOffset = p.X + 20;
                popup.VerticalOffset = p.Y + 10;
                popup.IsOpen = true;
                Animation(popupGrid, "Grid", "BlurEffect", 0.5, 30, 0);

                text5.Text = "Имя: " + info.name + "ИД: " + info.id;
                comment.commentId = info.id;
                comment.roadPodr = info.contractor;
                comment.roadStreet = info.name;
                comment.roadReit = info.reit;
            }
        }

        #endregion

        #region РЕЙТИНГ ДОРОГ И АЗС и т.д. и т.п.

        // Смена состояния дороги (из плохой в хорошую, и т.д.)
        private void Status(object sender)
        {
            string[] split = sender.ToString().Split('.');
            string type = split[split.Length - 1];
            
            switch (type)
            {
                case "Polyline":
                    {
                        #region Статус Дорога
                        Polyline obj = (Polyline)sender;
                        string name = obj.Name;
                        char roadstatus = name[name.Length - 1];
                        
                        switch (roadstatus)
                        {
                            case 'r':
                                {
                                    if (good.IsChecked.Value & listBoxRoad2.Items.Count < 10)
                                    {
                                        obj.Name = obj.Name.Substring(0, obj.Name.Length - 1) + "g";
                                        РейтингДорог(obj, 'r', 'g');
                                        ОкраскаПоСтатусу(obj);
                                    }
                                    else
                                    {
                                        obj.Name = obj.Name.Substring(0, obj.Name.Length - 1);
                                        РейтингДорог(obj, 'r', 'b');
                                        ОкраскаПоСтатусу(obj);
                                    }
                                    break;
                                }
                            case 'g':
                                {
                                    if (bad.IsChecked.Value & listBoxRoad1.Items.Count < 10)
                                    {
                                        obj.Name = obj.Name.Substring(0, obj.Name.Length - 1) + "r";
                                        РейтингДорог(obj, 'g', 'r');
                                        ОкраскаПоСтатусу(obj);
                                    }
                                    else
                                    {
                                        obj.Name = obj.Name.Substring(0, obj.Name.Length - 1);
                                        РейтингДорог(obj, 'g', 'b');
                                        ОкраскаПоСтатусу(obj);
                                    }
                                    break;
                                }
                            default:
                                {
                                    if (bad.IsChecked.Value & listBoxRoad1.Items.Count < 10)
                                    {
                                        obj.Name += "r";
                                        РейтингДорог(obj, 'b', 'r');
                                        ОкраскаПоСтатусу(obj);
                                    }
                                    else
                                    {
                                        if (good.IsChecked.Value & listBoxRoad2.Items.Count < 10)
                                        {
                                            obj.Name += "g";
                                            РейтингДорог(obj, 'b', 'g');
                                            ОкраскаПоСтатусу(obj);
                                        }
                                    }
                                    break;
                                }
                        }
                        #endregion
                        break;
                    }
                case "Image":
                    {
                        System.Windows.Controls.Image obj = (System.Windows.Controls.Image)sender;
                        string name = obj.Name;
                        string typeObject = name.Split('-')[0].ToString();
                        char roadstatus = name[name.Length - 1];
                        switch (typeObject)
                        {
                            case "GAS": 
                                {
                                    #region Статус АЗС
                                    switch (roadstatus)
                                    {
                                        case 'r': {
                                                if (good.IsChecked.Value & listBoxGAS2.Items.Count < 10)
                                                {
                                                    obj.Name = obj.Name.Substring(0, obj.Name.Length - 1) + "g";
                                                    РейтингДорог(obj, 'r', 'g');
                                                    ОкраскаПоСтатусу(obj);
                                                }
                                                else
                                                {
                                                    obj.Name = obj.Name.Substring(0, obj.Name.Length - 1);
                                                    РейтингДорог(obj, 'r', 'b');
                                                    ОкраскаПоСтатусу(obj);
                                                }
                                                break;
                                            }
                                        case 'g':
                                            {
                                                if (bad.IsChecked.Value & listBoxGAS1.Items.Count < 10)
                                                {
                                                    obj.Name = obj.Name.Substring(0, obj.Name.Length - 1) + "r";
                                                    РейтингДорог(obj, 'g', 'r');
                                                    ОкраскаПоСтатусу(obj);
                                                }
                                                else
                                                {
                                                    obj.Name = obj.Name.Substring(0, obj.Name.Length - 1);
                                                    РейтингДорог(obj, 'g', 'b');
                                                    ОкраскаПоСтатусу(obj);
                                                }
                                                break;
                                            }
                                        default:
                                            {
                                                if (bad.IsChecked.Value & listBoxGAS1.Items.Count < 10)
                                                {
                                                    obj.Name += "r";
                                                    РейтингДорог(obj, 'b', 'r');
                                                    ОкраскаПоСтатусу(obj);
                                                }
                                                else
                                                {
                                                    if (good.IsChecked.Value & listBoxGAS2.Items.Count < 10)
                                                    {
                                                        obj.Name += "g";
                                                        РейтингДорог(obj, 'b', 'g');
                                                        ОкраскаПоСтатусу(obj);
                                                    }
                                                }
                                                break;
                                            }
                                    
                                    }   
                                #endregion                                 
                                    break;                                    
                                }
                            case "Carwash":
                                {
                                    #region Статус Автомойка
                                    switch (roadstatus)
                                    {
                                        case 'r':
                                            {
                                                if (good.IsChecked.Value & listBoxCarwash2.Items.Count < 10)
                                                {
                                                    obj.Name = obj.Name.Substring(0, obj.Name.Length - 1) + "g";
                                                    РейтингДорог(obj, 'r', 'g');
                                                    ОкраскаПоСтатусу(obj);
                                                }
                                                else
                                                {
                                                    obj.Name = obj.Name.Substring(0, obj.Name.Length - 1);
                                                    РейтингДорог(obj, 'r', 'b');
                                                    ОкраскаПоСтатусу(obj);
                                                }
                                                break;
                                            }
                                        case 'g':
                                            {
                                                if (bad.IsChecked.Value & listBoxCarwash1.Items.Count < 10)
                                                {
                                                    obj.Name = obj.Name.Substring(0, obj.Name.Length - 1) + "r";
                                                    РейтингДорог(obj, 'g', 'r');
                                                    ОкраскаПоСтатусу(obj);
                                                }
                                                else
                                                {
                                                    obj.Name = obj.Name.Substring(0, obj.Name.Length - 1);
                                                    РейтингДорог(obj, 'g', 'b');
                                                    ОкраскаПоСтатусу(obj);
                                                }
                                                break;
                                            }
                                        default:
                                            {
                                                if (bad.IsChecked.Value & listBoxCarwash1.Items.Count < 10)
                                                {
                                                    obj.Name += "r";
                                                    РейтингДорог(obj, 'b', 'r');
                                                    ОкраскаПоСтатусу(obj);
                                                }
                                                else
                                                {
                                                    if (good.IsChecked.Value & listBoxCarwash2.Items.Count < 10)
                                                    {
                                                        obj.Name += "g";
                                                        РейтингДорог(obj, 'b', 'g');
                                                        ОкраскаПоСтатусу(obj);
                                                    }
                                                }
                                                break;
                                            }

                                    }
                                    #endregion                                 
                                    break;
                                }                        
                            default: {break;}
                        }                        
                        break;
                    }
            }

        }

        void РейтингДорог(object sender, char input, char output)
        {
            string type = sender.ToString().Split('.')[3];
            switch (type)
            {
                case "Polyline":
                    {
                        #region Добавление удаление из списка Дорога
                        Polyline thisroad = (Polyline)sender;                        
                        Perm._LoadRoads.LoadRoadsRoad info = thisroad.Tag as Perm._LoadRoads.LoadRoadsRoad;
                        string name = thisroad.Name.Split('-')[1];

                        switch (input)
                        {
                            case 'r':
                                {
                                    switch (output)
                                    {
                                        case 'g':
                                            {
                                                listBoxRoad2.Items.Add(name);                                                                                               
                                                if (listBoxRoad1.Items.Count != 0)
                                                {
                                                    for (int i = 0; i <= listBoxRoad1.Items.Count - 1; i++)
                                                    {
                                                        if (listBoxRoad1.Items[i].ToString() == name)
                                                        {
                                                            listBoxRoad1.Items.RemoveAt(i);
                                                        }
                                                    }
                                                }
                                                break;
                                            }
                                        case 'b':
                                            {
                                                if (listBoxRoad1.Items.Count != 0)
                                                {
                                                    for (int i = 0; i <= listBoxRoad1.Items.Count - 1; i++)
                                                    {
                                                        if (listBoxRoad1.Items[i].ToString() == name)
                                                        {
                                                            listBoxRoad1.Items.RemoveAt(i);
                                                        }
                                                    }
                                                }
                                                break;
                                            }
                                        default:
                                            { break; }
                                    }
                                    break;
                                }
                            case 'g':
                                {
                                    switch (output)
                                    {
                                        case 'r':
                                            {
                                                listBoxRoad1.Items.Add(name);
                                                if (listBoxRoad2.Items.Count != 0)
                                                {
                                                    for (int i = 0; i <= listBoxRoad2.Items.Count - 1; i++)
                                                    {
                                                        if (listBoxRoad2.Items[i].ToString() == name)
                                                        {
                                                            listBoxRoad2.Items.RemoveAt(i);
                                                        }
                                                    }
                                                }
                                                break;
                                            }
                                        case 'b':
                                            {
                                                if (listBoxRoad2.Items.Count != 0)
                                                {
                                                    for (int i = 0; i <= listBoxRoad2.Items.Count - 1; i++)
                                                    {
                                                        if (listBoxRoad2.Items[i].ToString() == name)
                                                        {
                                                            listBoxRoad2.Items.RemoveAt(i);
                                                        }
                                                    }
                                                }
                                                break;
                                            }
                                        default:
                                            { break; }
                                    }
                                    break;
                                }
                            case 'b':
                                {
                                    switch (output)
                                    {
                                        case 'r':
                                            {
                                                listBoxRoad1.Items.Add(name);
                                                break;
                                            }
                                        case 'g':
                                            {
                                                listBoxRoad2.Items.Add(name);
                                                break;
                                            }
                                        default:
                                            { break; }
                                    }
                                    break;
                                }
                            default:
                                { break; }
                        }
                        #endregion
                        break;
                    }
                case "Image":
                    {
                        System.Windows.Controls.Image thisImage = (System.Windows.Controls.Image)sender;                        
                        string nameimage = thisImage.Name.Split('-')[0];
                        
                        switch (nameimage)
                        {
                            case "GAS":
                                {
                                    #region Добавление удаление из списка АЗС
                                    Perm._GASstation.GASstationGAS info = thisImage.Tag as Perm._GASstation.GASstationGAS;
                                    string name = info.no.ToString();

                                    switch (input)
                                    {
                                        case 'r':
                                            {
                                                switch (output)
                                                {
                                                    case 'g':
                                                        {
                                                            listBoxGAS2.Items.Add(name);
                                                            if (listBoxGAS1.Items.Count != 0)
                                                            {
                                                                for (int i = 0; i <= listBoxGAS1.Items.Count - 1; i++)
                                                                {
                                                                    if (listBoxGAS1.Items[i].ToString() == name)
                                                                    {
                                                                        listBoxGAS1.Items.RemoveAt(i);
                                                                    }
                                                                }
                                                            }
                                                            break;
                                                        }
                                                    case 'b':
                                                        {
                                                            if (listBoxGAS1.Items.Count != 0)
                                                            {
                                                                for (int i = 0; i <= listBoxGAS1.Items.Count - 1; i++)
                                                                {
                                                                    if (listBoxGAS1.Items[i].ToString() == name)
                                                                    {
                                                                        listBoxGAS1.Items.RemoveAt(i);
                                                                    }
                                                                }
                                                            }
                                                            break;
                                                        }
                                                    default:
                                                        { break; }
                                                }
                                                break;
                                            }
                                        case 'g':
                                            {
                                                switch (output)
                                                {
                                                    case 'r':
                                                        {
                                                            listBoxGAS1.Items.Add(name);
                                                            if (listBoxGAS2.Items.Count != 0)
                                                            {
                                                                for (int i = 0; i <= listBoxGAS2.Items.Count - 1; i++)
                                                                {
                                                                    if (listBoxGAS2.Items[i].ToString() == name)
                                                                    {
                                                                        listBoxGAS2.Items.RemoveAt(i);
                                                                    }
                                                                }
                                                            }
                                                            break;
                                                        }
                                                    case 'b':
                                                        {
                                                            if (listBoxGAS2.Items.Count != 0)
                                                            {
                                                                for (int i = 0; i <= listBoxGAS2.Items.Count - 1; i++)
                                                                {
                                                                    if (listBoxGAS2.Items[i].ToString() == name)
                                                                    {
                                                                        listBoxGAS2.Items.RemoveAt(i);
                                                                    }
                                                                }
                                                            }
                                                            break;
                                                        }
                                                    default:
                                                        { break; }
                                                }
                                                break;
                                            }
                                        case 'b':
                                            {
                                                switch (output)
                                                {
                                                    case 'r':
                                                        {
                                                            listBoxGAS1.Items.Add(name);
                                                            break;
                                                        }
                                                    case 'g':
                                                        {
                                                            listBoxGAS2.Items.Add(name);
                                                            break;
                                                        }
                                                    default:
                                                        { break; }
                                                }
                                                break;
                                            }
                                        default:
                                            { break; }
                                    }
                                    #endregion
                                    break;
                                }
                            case "Carwash":
                                {
                                    #region Добавление удаление из списка Автомойка
                                    Perm._CarWash.CarWashCarwash info = thisImage.Tag as Perm._CarWash.CarWashCarwash;
                                    string name = info.no.ToString();

                                    switch (input)
                                    {
                                        case 'r':
                                            {
                                                switch (output)
                                                {
                                                    case 'g':
                                                        {
                                                            listBoxCarwash2.Items.Add(name);
                                                            if (listBoxCarwash1.Items.Count != 0)
                                                            {
                                                                for (int i = 0; i <= listBoxCarwash1.Items.Count - 1; i++)
                                                                {
                                                                    if (listBoxCarwash1.Items[i].ToString() == name)
                                                                    {
                                                                        listBoxCarwash1.Items.RemoveAt(i);
                                                                    }
                                                                }
                                                            }
                                                            break;
                                                        }
                                                    case 'b':
                                                        {
                                                            if (listBoxCarwash1.Items.Count != 0)
                                                            {
                                                                for (int i = 0; i <= listBoxCarwash1.Items.Count - 1; i++)
                                                                {
                                                                    if (listBoxCarwash1.Items[i].ToString() == name)
                                                                    {
                                                                        listBoxCarwash1.Items.RemoveAt(i);
                                                                    }
                                                                }
                                                            }
                                                            break;
                                                        }
                                                    default:
                                                        { break; }
                                                }
                                                break;
                                            }
                                        case 'g':
                                            {
                                                switch (output)
                                                {
                                                    case 'r':
                                                        {
                                                            listBoxCarwash1.Items.Add(name);
                                                            if (listBoxCarwash2.Items.Count != 0)
                                                            {
                                                                for (int i = 0; i <= listBoxCarwash2.Items.Count - 1; i++)
                                                                {
                                                                    if (listBoxCarwash2.Items[i].ToString() == name)
                                                                    {
                                                                        listBoxCarwash2.Items.RemoveAt(i);
                                                                    }
                                                                }
                                                            }
                                                            break;
                                                        }
                                                    case 'b':
                                                        {
                                                            if (listBoxCarwash2.Items.Count != 0)
                                                            {
                                                                for (int i = 0; i <= listBoxCarwash2.Items.Count - 1; i++)
                                                                {
                                                                    if (listBoxCarwash2.Items[i].ToString() == name)
                                                                    {
                                                                        listBoxCarwash2.Items.RemoveAt(i);
                                                                    }
                                                                }
                                                            }
                                                            break;
                                                        }
                                                    default:
                                                        { break; }
                                                }
                                                break;
                                            }
                                        case 'b':
                                            {
                                                switch (output)
                                                {
                                                    case 'r':
                                                        {
                                                            listBoxCarwash1.Items.Add(name);
                                                            break;
                                                        }
                                                    case 'g':
                                                        {
                                                            listBoxCarwash2.Items.Add(name);
                                                            break;
                                                        }
                                                    default:
                                                        { break; }
                                                }
                                                break;
                                            }
                                        default:
                                            { break; }
                                    }
                                    #endregion
                                    break;
                                }
                            default: {break;}
                        }                        
                        break;
                    }
            }
        }  

        //Окраска дорог в зависимости от статуса
        private void ОкраскаПоСтатусу(object sender)
        {
            string type = sender.ToString().Split('.')[sender.ToString().Split('.').Length - 1];
            switch (type)
            {
                case "Polyline":
                    {
                        #region Окраска в зависимости от текущего состояния Дорога
                        Polyline obj = (Polyline)sender;
                        string name = obj.Name.ToString();
                        char status = name[name.Length - 1];
                        switch (status)
                        {
                            case 'r':
                                {
                                    obj.Stroke = RED;
                                    obj.StrokeThickness = (city != "permkray") ? 32 : 32 * strokePermkray; ;
                                    break;
                                }
                            case 'g':
                                {
                                    obj.Stroke = GREEN2;
                                    obj.StrokeThickness = (city != "permkray") ? 32 : 32 * strokePermkray; ;
                                    break;
                                }
                            default:
                                {
                                    obj.Stroke = GREY;
                                    obj.StrokeThickness = (city != "permkray") ? 16 : 16 * strokePermkray; ;
                                    break;
                                }
                        }
                        #endregion
                        break;
                    }
                case "Image":
                    {
                        System.Windows.Controls.Image obj = (System.Windows.Controls.Image)sender;                        
                        string name = obj.Name.ToString();
                        string typeObject = name.Split('-')[0].ToString();
                        char status = name[name.Length - 1];

                        switch (typeObject)
                        {
                            case "GAS":
                                {
                                    #region Окраска в зависимости от текущего состояния АЗС
                                    switch (status)
                                    {
                                        case 'r':
                                            {
                                                obj.Source = new BitmapImage(new Uri("../Images/gas_red2.png", UriKind.RelativeOrAbsolute));
                                                break;
                                            }
                                        case 'g':
                                            {
                                                obj.Source = new BitmapImage(new Uri("../Images/gas_green2.png", UriKind.RelativeOrAbsolute));
                                                break;
                                            }
                                        default:
                                            {
                                                obj.Source = new BitmapImage(new Uri("../Images/gas2.png", UriKind.RelativeOrAbsolute));
                                                break;
                                            }
                                    }
                                    #endregion
                                    break;
                                }
                            case "Carwash":
                                {
                                    #region Окраска в зависимости от текущего состояния Автомойка
                                    switch (status)
                                    {
                                        case 'r':
                                            {
                                                obj.Source = new BitmapImage(new Uri("../Images/carwash_red2.png", UriKind.RelativeOrAbsolute));
                                                break;
                                            }
                                        case 'g':
                                            {
                                                obj.Source = new BitmapImage(new Uri("../Images/carwash_green2.png", UriKind.RelativeOrAbsolute));
                                                break;
                                            }
                                        default:
                                            {
                                                obj.Source = new BitmapImage(new Uri("../Images/carwash2.png", UriKind.RelativeOrAbsolute));
                                                break;
                                            }
                                    }
                                    #endregion
                                    break;
                                }
                            default: {break;}
                        }
                        break;
                    }
            }
        }
                        
        
        #endregion

        #region СТРОЕНИЯ (ЗАГРУЗКА)

        void proxyLoadHouses_DoWorkCompleted(object sender, _LoadHouses.DoWorkCompletedEventArgs e)
        {
            ObservableCollection<_LoadHouses.LoadHousesHouse> getHouse = e.Result;
            

            for (iHouse = 0; iHouse <= getHouse.Count - 1; iHouse++)
            {                
                Polygon House_Polygon = new Polygon();
                PointCollection House_Pointcol = new PointCollection();
                Point House_Pointcol_Point = new Point();

                House_Polygon.StrokeThickness = 1;
                House_Polygon.Stroke = BLACK;
                House_Polygon.Fill = new SolidColorBrush(Color.FromArgb(255, 230, 230, 230));

                int id = getHouse[iHouse].id;

                House_Polygon.Name = "House-" + id.ToString();
                House_Polygon.Tag = getHouse[iHouse];

                string[] X = getHouse[iHouse].X.Split(';');
                string[] Y = getHouse[iHouse].Y.Split(';');

                for (int j = 0; j < X.Length - 1; j++)
                {
                    House_Pointcol_Point.X = double.Parse(X[j]); ;
                    House_Pointcol_Point.Y = -double.Parse(Y[j]);

                    House_Polygon.Points = House_Pointcol;
                    House_Pointcol.Add(House_Pointcol_Point);
                }

                //Тень
                #region ЭФФЕКТ ТЕНЬ                
                shadow.Direction = 320;
                shadow.ShadowDepth = 10;
                shadow.BlurRadius = 0;
                shadow.Opacity = 0.5;

                Color myShadowColor = new Color();
                myShadowColor.A = 255;
                myShadowColor.B = 50;
                myShadowColor.G = 50;
                myShadowColor.R = 50;

                shadow.Color = myShadowColor;
                #endregion

                House.Children.Add(House_Polygon);
                House_Polygon.MouseEnter += new MouseEventHandler(House_Polygon_MouseEnter);
            }
            loadTimerHouse.Stop();
            progressBar1.Value = progressBar1.Maximum;
            TextLayer.Text = "Загрузка строений завершена";
            Loader.Visibility = Visibility.Collapsed;
            main.Visibility = Visibility.Visible; 
        }

        void House_Polygon_MouseEnter(object sender, MouseEventArgs e)
        {
         
            Polygon HOUSE = (Polygon)e.OriginalSource;
            Perm._LoadHouses.LoadHousesHouse info = HOUSE.Tag as Perm._LoadHouses.LoadHousesHouse;
            text5.Text = "ИД: " + info.id;
        }

        #endregion

        #region ЛАНДШАФТ
        void loadLandscape()
        {
            LoadRivers();
            LoadGreens();
            loadTimerLandscape.Interval = new TimeSpan(0, 0, 0, 0, 1);
            loadTimerLandscape.Tick += new EventHandler(loadTimerLandscape_Tick);
            loadTimerLandscape.Start();
            progressBar1.Value = 0;
            progressBar1.Maximum = 2000;
            TextLayer.Text = "Загрузка ландшафта";
        }

        //Реки
        void proxyRivers_DoWorkCompleted(object sender, _Rivers.DoWorkCompletedEventArgs e)
        {
            ObservableCollection<_Rivers.RiversRiver> getRiver = e.Result;


            for (iRiver = 0; iRiver <= getRiver.Count - 1; iRiver++)
            {
                Polygon River_Polygon = new Polygon();
                PointCollection River_Pointcol = new PointCollection();
                Point River_Pointcol_Point = new Point();

                River_Polygon.Fill = new SolidColorBrush(Color.FromArgb(255, 140, 179, 243));

                int id = getRiver[iRiver].id;

                River_Polygon.Name = "River-" + id.ToString();
                River_Polygon.Tag = getRiver[iRiver];

                string[] X = getRiver[iRiver].X.Split(';');
                string[] Y = getRiver[iRiver].Y.Split(';');

                for (int j = 0; j < X.Length - 1; j++)
                {
                    River_Pointcol_Point.X = (city != "permkray") ? double.Parse(X[j]) : double.Parse(X[j]) - permkrayX;
                    River_Pointcol_Point.Y = (city != "permkray") ? -double.Parse(Y[j]) : -double.Parse(Y[j]) + permkrayY;

                    River_Polygon.Points = River_Pointcol;
                    River_Pointcol.Add(River_Pointcol_Point);
                }
                Map.Children.Add(River_Polygon);
            }            
            loadTimerLandscape.Stop();
            progressBar1.Value = progressBar1.Maximum;
            TextLayer.Text = "Загрузка ландшафта завершена";
            Loader.Visibility = Visibility.Collapsed;
            main.Visibility = Visibility.Visible; 
        }
        //Зелень
        void proxyGreens_DoWorkCompleted(object sender, _Greens.DoWorkCompletedEventArgs e)
        {
            ObservableCollection<_Greens.GreensGreen> getGreen = e.Result;
            
            for (iGreen = 0; iGreen <= getGreen.Count - 1; iGreen++)
            {
                /*
                Polygon Green_Polygon = new Polygon();
                PointCollection Green_Pointcol = new PointCollection();
                Point Green_Pointcol_Point = new Point();

                Green_Polygon.Fill = new SolidColorBrush(Color.FromArgb(255, 157, 243, 140));

                int id = getGreen[iGreen].id;

                Green_Polygon.Name = "Green-" + id.ToString();
                Green_Polygon.Tag = getGreen[iGreen];

                string[] X = getGreen[iGreen].X.Split(';');
                string[] Y = getGreen[iGreen].Y.Split(';');

                for (int j = 0; j < X.Length - 1; j++)
                {
                    Green_Pointcol_Point.X = double.Parse(X[j]); ;
                    Green_Pointcol_Point.Y = -double.Parse(Y[j]);

                    Green_Polygon.Points = Green_Pointcol;
                    Green_Pointcol.Add(Green_Pointcol_Point);
                }
                */
                
                Map.Children.Add(createPath(getGreen));
            }
        }

        System.Windows.Shapes.Path createPath(ObservableCollection<_Greens.GreensGreen> rawData)
        {
            System.Windows.Shapes.Path FinalPath = new System.Windows.Shapes.Path();            
            PathGeometry FinalPathGeometry = new PathGeometry();
            PathFigure PrimaryFigure = new PathFigure(); 

            PrimaryFigure.IsClosed = false;
            FinalPath.Fill = new SolidColorBrush(Color.FromArgb(255, 157, 243, 140));
            FinalPath.Tag = rawData[iGreen];

            double x1 = double.Parse(rawData[iGreen].X.Split(';')[0]);
            double y1 = -double.Parse(rawData[iGreen].Y.Split(';')[0]);

            PrimaryFigure.StartPoint = new Point(x1, y1);

            PathSegmentCollection LineSegmentCollection = new PathSegmentCollection();
            for (int i = 1; i < rawData[iGreen].X.Split(';').Length - 1; i++)
            {
                LineSegment newSegment = new LineSegment();
                double x = double.Parse(rawData[iGreen].X.Split(';')[i]);
                double y = -double.Parse(rawData[iGreen].Y.Split(';')[i]);
                newSegment.Point = new Point(x, y);
                LineSegmentCollection.Add(newSegment);
            }
            PrimaryFigure.Segments = LineSegmentCollection;
            FinalPathGeometry.Figures.Add(PrimaryFigure);
            FinalPath.Data = FinalPathGeometry;
            FinalPath.MouseEnter += new MouseEventHandler(FinalPath_MouseEnter);
            
            return FinalPath;
        }

        void FinalPath_MouseEnter(object sender, MouseEventArgs e)
        {
            System.Windows.Shapes.Path GREEN = (System.Windows.Shapes.Path)sender;
            Perm._Greens.GreensGreen info = GREEN.Tag as Perm._Greens.GreensGreen;
            text5.Text = "ИД: " + info.id;
        }
        #endregion
        #region IP
        //Получение IP адреса
        public class User
        {
            public string ip { get; set; }
            public string browser { get; set; }
        }

        void getIP()
        {
            WebClient wbcl = new WebClient();
            wbcl.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wbcl_DownloadStringCompleted);
            //адрес PHP файла с функцией получения IP
            Uri myUri = new Uri("http://permnext.ru/Image_P/index.php", UriKind.Absolute);            
            wbcl.DownloadStringAsync(myUri);
        }

        void wbcl_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("Невозможно получить IP адрес клиента.\r\n" + e.Error.Message, "IP адрес", MessageBoxButton.OK);
                IP.Text = "IP-адрес не получен";
                RoadReating.IsEnabled = true;
                return;
            }
            DataContractJsonSerializer serializer =
            new DataContractJsonSerializer(typeof(User));

            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(e.Result));
            User deserializedUser = new User();
            Type tp = deserializedUser.GetType();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(tp);

            deserializedUser = (User)ser.ReadObject(ms);
            ms.Close();
            if (deserializedUser.ip.ToString() != "")
            {
                IP.Text = "IP " + deserializedUser.ip.ToString();
            }
            CheckVote(IP.Text.Split(' ')[1]);
        }
        #endregion

        #region Все основные и дополнительные функции

        void addImage()
        {

            //wb = new WriteableBitmap(main, null);
            //wb.Invalidate();
            wb = new WriteableBitmap((int)(main.ActualWidth + main.ActualWidth / 2), (int)(main.ActualHeight + main.ActualHeight / 2));
            wb.Render(main, new MatrixTransform());
            wb.Invalidate();
            image1.Source = wb;
        }
        //Вывод информации, текущих данных позиционирования
        private void getInfo(MouseEventArgs e)
        {
            text.Text = "translate (x, y): " + (r2(e.GetPosition(translate).X)).ToString() + "   " + (r2(e.GetPosition(translate).Y)).ToString();
            text2.Text = "MyTranslate: " + r2(MyTranslate.X).ToString() + "   " + r2(MyTranslate.Y).ToString();
            text3.Text = "nach: " + r2(nach.X).ToString() + "   " + r2(nach.Y).ToString();
            text4.Text = "city: " + city;
            zoom1.Text = "zoom: " + zoom.ToString();
            getObject.Text = e.OriginalSource.ToString().Split('.')[3];
        }
        //Процедура увеличения
        void zoomProcedure(double zoom, Point P)
        {
            if (P != null)
            {
                double dX = P.X * MyScale.ScaleX - P.X * zoom;
                double dY = P.Y * MyScale.ScaleY - P.Y * zoom;
                MyTranslate.X += dX;
                MyTranslate.Y += dY;
                nach.X = MyTranslate.X;
                nach.Y = MyTranslate.Y;
            }
            MyScale.ScaleX = zoom;
            MyScale.ScaleY = zoom;
        }
//Вывод количества комментариев
        void proxygetCountComments_DoWorkCompleted(object sender, _getCountComments.DoWorkCompletedEventArgs e)
        {
            popupText4.Text = "Комментарии (" + e.Result + ")";
        }

//Вывод количества голосов
        void proxygetCountVote_DoWorkCompleted(object sender, _getCountVote.DoWorkCompletedEventArgs e)
        {
            currentVote = e.Result;
            if (VOTE.Text != currentVote.ToString())
            {
                VOTE.Text = currentVote.ToString();
                VOTE2.Text = currentVote.ToString();
                VOTE3.Text = currentVote.ToString();
            }
        }

//Окраска
        void Colored(object sender, int reit)
        {
            string type = sender.ToString().Split('.')[3];
            switch (type)
            {
                case "Polyline":
                    {
                        #region Раскидываем по слоям в зависимости от рейтинга Дороги

                        Polyline obj = (Polyline)sender;
                        if (reit < 0)
                        {
                            byte color = Convert.ToByte(255 - (255 / Math.Abs(MINrait) * Math.Abs(reit)));
                           
                            obj.Stroke = new SolidColorBrush(Color.FromArgb(255, 255, color, 0));
                        }
                        else if (reit > 0)
                        {
                            byte color = Convert.ToByte(255 - (255 / MAXrait * reit));

                            obj.Stroke = new SolidColorBrush(Color.FromArgb(255, color, 255, 0));
                        }
                        if (obj.Parent != null & reit==0)
                            {
                                ((Canvas)obj.Parent).Children.Remove(obj);
                            }
                            else if (obj.Parent == null)
                            {
                                if (reit >= r2(MAXrait / 3 * 2))
                                {
                                    Raiting_1.Children.Add(obj);
                                }
                                if (reit >= r2(MAXrait / 3) & reit < r2(MAXrait / 3 * 2))
                                {
                                    Raiting_2.Children.Add(obj);
                                }
                                if (reit > 0 & reit < r2(MAXrait / 3))
                                {
                                    Raiting_3.Children.Add(obj);
                                }
                                if (reit < 0 & reit > r2(MINrait / 3))
                                {
                                    Raiting_4.Children.Add(obj);
                                }
                                if (reit <= r2(MINrait / 3) & reit > r2(MINrait / 3 * 2))
                                {
                                    Raiting_5.Children.Add(obj);
                                }
                                if (reit <= r2(MINrait / 3 * 2))
                                {
                                    Raiting_6.Children.Add(obj);
                                }
                        #endregion
                             
                        }              
                        break;
                    }
                case "Border":
                    {
                        
                        Border obj = (Border)sender;
                        string typeObject = obj.Name.ToString().Split('-')[0].ToString();
                        switch (typeObject)
                        {
                            case "GAS":
                                {
                                    #region Раскидываем по слоям в зависимости от рейтинга АЗС
                                    if (reit < 0)
                                    {

                                        byte color = (byte)(255 - (255 / Math.Abs(MINraitGAS) * Math.Abs(reit)));
                                        obj.Background = new SolidColorBrush(Color.FromArgb(255, 255, color, 0));
                                    }
                                    else if (reit > 0)
                                    {
                                        byte color = (byte)(255 - (255 / MAXraitGAS * reit));
                                        obj.Background = new SolidColorBrush(Color.FromArgb(255, color, 255, 0));
                                    }
                                    if (obj.Parent != null & reit == 0)
                                    {
                                        ((Canvas)obj.Parent).Children.Remove(obj);
                                    }
                                    else if (obj.Parent == null)
                                    {
                                            if (reit > r2(MAXraitGAS / 3 * 2))
                                            {
                                                StationRaiting_1.Children.Add(obj);
                                            }
                                            if (reit >= r2(MAXraitGAS / 3) & reit < r2(MAXraitGAS / 3 * 2))
                                            {
                                                StationRaiting_2.Children.Add(obj);
                                            }
                                            if (reit > 0 & reit < r2(MAXraitGAS / 3))
                                            {
                                                StationRaiting_3.Children.Add(obj);
                                            }
                                            if (reit < 0 & reit > r2(MINraitGAS / 3))
                                            {
                                                StationRaiting_4.Children.Add(obj);
                                            }
                                            if (reit <= r2(MINraitGAS / 3) & reit > r2(MINraitGAS / 3 * 2))
                                            {
                                                StationRaiting_5.Children.Add(obj);
                                            }
                                            if (reit <= r2(MINraitGAS / 3 * 2))
                                            {
                                                StationRaiting_6.Children.Add(obj);
                                            }
                                        }
                                    #endregion
                                    break;
                                }
                            case "Carwash":
                                {
                                    #region Раскидываем по слоям в зависимости от рейтинга Автомойки
                                    if (reit < 0)
                                    {

                                        byte color = (byte)(255 - (255 / Math.Abs(MINraitCarwash) * Math.Abs(reit)));
                                        obj.Background = new SolidColorBrush(Color.FromArgb(255, 255, color, 0));
                                    }
                                    else if (reit > 0)
                                    {
                                        byte color = (byte)(255 - (255 / MAXraitCarwash * reit));
                                        obj.Background = new SolidColorBrush(Color.FromArgb(255, color, 255, 0));
                                    }
                                    if (obj.Parent != null & reit == 0)
                                    {
                                        ((Canvas)obj.Parent).Children.Remove(obj);
                                    }
                                    else if (obj.Parent == null)
                                    {
                                            if (reit > r2(MAXraitCarwash / 3 * 2))
                                            {
                                                CarwashRaiting_1.Children.Add(obj);
                                            }
                                            if (reit >= r2(MAXraitCarwash / 3) & reit < r2(MAXraitCarwash / 3 * 2))
                                            {
                                                CarwashRaiting_2.Children.Add(obj);
                                            }
                                            if (reit > 0 & reit < r2(MAXraitCarwash / 3))
                                            {
                                                CarwashRaiting_3.Children.Add(obj);
                                            }
                                            if (reit < 0 & reit > r2(MINraitCarwash / 3))
                                            {
                                                CarwashRaiting_4.Children.Add(obj);
                                            }
                                            if (reit <= r2(MINraitCarwash / 3) & reit > r2(MINraitCarwash / 3 * 2))
                                            {
                                                CarwashRaiting_5.Children.Add(obj);
                                            }
                                            if (reit <= r2(MINraitCarwash / 3 * 2))
                                            {
                                                CarwashRaiting_6.Children.Add(obj);
                                            }
                                        }
                                    #endregion
                                    break;
                                }
                        }
                        
                        break;
                    }
            }
        }

        void LoadSQ(Point start, Point end)
        {
            if (zoom > 0.7)
            {
                LoadHouse();
            }
        }

//округление до 2х знаков после точки
        public double r2(double number)
        {
            return Math.Round(number, 2);
        }

//Вывод TOP АЗС и дорог
        void proxyMM_DoWorkCompleted(object sender, _MM.DoWorkCompletedEventArgs e)
        {
            listBoxRoadGood.ItemsSource = e.Result[0];
            listBoxRoadBad.ItemsSource = e.Result[1];
            listBoxGasGood.ItemsSource = e.Result[2];
            listBoxGasBad.ItemsSource = e.Result[3];
            listBoxCarwashGood.ItemsSource = e.Result[4];
            listBoxCarwashBad.ItemsSource = e.Result[5];
        }

        //Проверко голосования по IP и запрет голосования
        void proxyCheckVote_DoWorkCompleted(object sender, _CheckVote.DoWorkCompletedEventArgs e)
        {
            if (CONFIG_CHECK_IP)
            {
                if (e.Result != null)
                {
                    checkVote.Text = e.Result;
                    RoadReating.IsEnabled = false;
                }
                else
                {
                    RoadReating.IsEnabled = true;
                }
            }
            else RoadReating.IsEnabled = true;
        }

        void fillMinMaxRaiting(int tabIndex)
        {
            double MAX, MIN;
            switch (tabIndex)
            {
                case 1:
                    {
                        MAX = MAXraitGAS; MIN = MINraitGAS;
                        break;
                    }
                case 2:
                    {
                        MAX = MAXraitCarwash; MIN = MINraitCarwash;
                        break;
                    }

                default:
                    {
                        MAX = MAXrait; MIN = MINrait;
                        break;
                    }
            }            
            MAX = (MAX != 1.1) ? MAX : 0;
            MIN = (MIN != 1.1) ? MIN : 0;
            ReitingVisible_1.Content = "Рейтинг " + r2(MAX / 3 * 2) + "..max (" + MAX + ")";
            ReitingVisible_2.Content = "Рейтинг " + r2(MAX / 3) + ".." + r2(MAX / 3 * 2);
            ReitingVisible_3.Content = "Рейтинг 0.." + r2(MAX / 3);
            ReitingVisible_4.Content = "Рейтинг " + r2(MIN / 3) + "..0";
            ReitingVisible_5.Content = "Рейтинг " + r2(MIN / 3 * 2) + ".." + r2(MIN / 3);
            ReitingVisible_6.Content = "Рейтинг min (" + MIN + ").." + r2(MIN / 3 * 2);
        }

        //Вывод Максимального, Минимального рейтинга и общего количества голосов
        void proxyMaaxMin_DoWorkCompleted(object sender, _RaitingMaxMin.DoWorkCompletedEventArgs e)
        {
                MAXrait = (e.Result[0] != 0.0) ? e.Result[0] : 1.1;
                MINrait = (e.Result[1] != 0.0) ? e.Result[1] : 1.1;
                MAXraitGAS = (e.Result[2] != 0.0) ? e.Result[2] : 1.1;
                MINraitGAS = (e.Result[3] != 0.0) ? e.Result[3] : 1.1;
                MAXraitCarwash = (e.Result[4] != 0.0) ? e.Result[4] : 1.1;
                MINraitCarwash = (e.Result[5] != 0.0) ? e.Result[5] : 1.1;

            commentsText.Text = "КОММЕНТАРИИ по проекту (" + e.Result[6].ToString() + ")";

            TabControl tab = new TabControl();
            fillMinMaxRaiting(tab.SelectedIndex); 
 
            loadTimerRaiting.Stop();
            progressBar1.Value = progressBar1.Maximum;
            TextLayer.Text = "Загрузка рейтинга завершена";
            if (!flagVote)
            {
                flagVote = true;
                if (CONFIG_LOAD_GAS) GASstation();
            }
        }

        //Сохранение изменений рейтинга
        void proxySaveReiting_DoWorkCompleted(object sender, _SaveReiting.DoWorkCompletedEventArgs e)
        {
            //msg.info.Text = e.Result;
            //msg.Show();
            MessageBox.Show(e.Result,"", MessageBoxButton.OK);
            
            if (e.Result.Substring(0, 5) != "Ошибка")
            {
                RoadReating.IsEnabled = false;
                ResetReiting();
            }
        }

        //Сброс отметко о рейтинге
        void ResetReiting()
        {            
            bad.IsChecked = false;
            good.IsChecked = true;
            if (listBoxRoad2.Items.Count != 0)
            {
                for (int i = 0; i < listBoxRoad2.Items.Count + 1; i++)
                {
                    Polyline road = (Polyline)FindName("Road-" + listBoxRoad2.Items[0].ToString() + "-g");
                    //Status(road);
                }
            }
            if (listBoxGAS2.Items.Count != 0)
            {
                for (int i = 0; i < listBoxGAS2.Items.Count + 1; i++)
                {
                    System.Windows.Controls.Image gas = (System.Windows.Controls.Image)FindName("GAS-image-" + listBoxGAS2.Items[i].ToString() + "-g");
                    //Status(gas);

                }
            }
            if (listBoxCarwash2.Items.Count != 0)
            {
                for (int i = 0; i < listBoxCarwash2.Items.Count + 1; i++)
                {
                    System.Windows.Controls.Image carwash = (System.Windows.Controls.Image)FindName("Carwash-image-" + listBoxCarwash2.Items[i].ToString() + "-g");
                    //Status(carwash);
                }
            }

            bad.IsChecked = true;
            good.IsChecked = false;
            if (listBoxRoad1.Items.Count != 0)
            {
                for (int i = 0; i < listBoxRoad1.Items.Count + 1; i++)
                {
                    Polyline road = (Polyline)FindName("Road-" + listBoxRoad1.Items[0].ToString() + "-r");
                    //Status(road);
                }
            }
            if (listBoxGAS1.Items.Count != 0)
            {
                for (int i = 0; i < listBoxGAS1.Items.Count + 1; i++)
                {
                    System.Windows.Controls.Image gas = (System.Windows.Controls.Image)FindName("GAS-image-" + listBoxGAS1.Items[i].ToString() + "-r");
                    //Status(gas);
                }
            }
            if (listBoxCarwash1.Items.Count != 0)
            {
                for (int i = 0; i < listBoxCarwash1.Items.Count + 1; i++)
                {
                    System.Windows.Controls.Image carwash = (System.Windows.Controls.Image)FindName("Carwash-image-" + listBoxCarwash1.Items[i].ToString() + "-r");
                    //Status(carwash);
                }
            }     
        }

        //Очистка канвасов
        void Clean()
        {
            //Loader.Visibility = Visibility.Visible;
            //main.Visibility = Visibility.Collapsed;
            Station.Children.Clear();
            Roads.Children.Clear();
            Streets.Children.Clear();
            Raiting_1.Children.Clear();
            Raiting_2.Children.Clear();
            Raiting_3.Children.Clear();
            Raiting_4.Children.Clear();
            Raiting_5.Children.Clear();
            Raiting_6.Children.Clear();
            StationRaiting_1.Children.Clear();
            StationRaiting_2.Children.Clear();
            StationRaiting_3.Children.Clear();
            StationRaiting_4.Children.Clear();
            StationRaiting_5.Children.Clear();
            StationRaiting_6.Children.Clear();
            CarwashRaiting_1.Children.Clear();
            CarwashRaiting_2.Children.Clear();
            CarwashRaiting_3.Children.Clear();
            CarwashRaiting_4.Children.Clear();
            CarwashRaiting_5.Children.Clear();
            CarwashRaiting_6.Children.Clear();
            zoom = 0.02;
        }

// Копирование объекта!!!!
        public static T Clone<T>(T source)
        {
            T cloned = (T)Activator.CreateInstance(source.GetType());

            foreach (PropertyInfo curPropInfo in source.GetType().GetProperties())
            {
                if (curPropInfo.GetGetMethod() != null
                    && (curPropInfo.GetSetMethod() != null))
                {
                    // Handle Non-indexer properties
                    if (curPropInfo.Name != "Item")
                    {
                        // get property from source
                        object getValue = curPropInfo.GetGetMethod().Invoke(source, new object[] { });

                        // clone if needed
                        if (getValue != null && getValue is DependencyObject)
                            getValue = Clone((DependencyObject)getValue);

                        // set property on cloned
                        if (getValue != null && getValue.ToString() != "")
                            curPropInfo.GetSetMethod().Invoke(cloned, new object[] { getValue });
                    }
                    // handle indexer
                    else
                    {
                        // get count for indexer
                        int numberofItemInColleciton =
                            (int)
                            curPropInfo.ReflectedType.GetProperty("Count").GetGetMethod().Invoke(source, new object[] { });

                        // run on indexer
                        for (int i = 0; i < numberofItemInColleciton; i++)
                        {
                            // get item through Indexer
                            object getValue = curPropInfo.GetGetMethod().Invoke(source, new object[] { i });

                            // clone if needed
                            if (getValue != null && getValue is DependencyObject)
                                getValue = Clone((DependencyObject)getValue);
                            // add item to collection
                            curPropInfo.ReflectedType.GetMethod("Add").Invoke(cloned, new object[] { getValue });
                        }
                    }
                }
            }

            return cloned;
        }
//Процедура анимации (изменение параметров эффекта и т.д.)
        #region АНИМАЦИЯ с добавлением эффекта
        void Animation(object sender, string type, string effecttype, double time, double InValue, double OutValue)
        {
            DependencyObject depObj = (DependencyObject)sender;

            switch (effecttype)
            {
                case "BlurEffect":
                    {
                        blur.Radius = InValue;
                        depObj = blur;
                        switch (type)
                        {
                            case "Grid":
                                {
                                    Grid obj = (Grid)sender;
                                    obj.Effect = blur;
                                    break;
                                }
                            default: { break; }
                        }
                        break;
                    }
                case "DropShadowEffect":
                    {
                        break;
                    }
                case "PixelShader":
                    {
                        break;
                    }
                case "ScaleX":
                    {
                        depObj = MyScale;
                        break;
                    }
                case "ScaleY":
                    {
                        depObj = MyScale;
                        break;
                    }
                default: { break; }
            }

            //Устаналиваем длительность 1 сек
            //в данном случае длительность анимации и всей коллекции совпадают
            Duration duration = new Duration(TimeSpan.FromSeconds(time));

            //создаем анимацию
            DoubleAnimation da = new DoubleAnimation();
            //Создаем коллекцию анимаций Storyboard
            Storyboard sb = new Storyboard();

            //Задаем длительность
            da.Duration = duration;
            sb.Duration = duration;

            //Устанавливаем объект к которому будет применятся анимация
            Storyboard.SetTarget(da, depObj);
            if (effecttype == "BlurEffect")
            {
                //Устанавливаем свойство, которое будем изменять
                Storyboard.SetTargetProperty(da, new PropertyPath("Radius"));
            }
            if (effecttype == "ScaleX")
            {
                //Устанавливаем свойство, которое будем изменять
                Storyboard.SetTargetProperty(da, new PropertyPath("ScaleX"));
            }
            if (effecttype == "ScaleY")
            {
                //Устанавливаем свойство, которое будем изменять
                Storyboard.SetTargetProperty(da, new PropertyPath("ScaleY"));
            }
            //Устанавливаем новое значение свойства
            da.To = OutValue;
            //Добавляем в коллекцию
            sb.Children.Add(da);
            //начинаем анимацию
            sb.Begin();
        }
        #endregion
        #endregion
        
        public MainPage()
        {
            InitializeComponent();

        #region ZOOM и MOVE
//Увеличение и перемещение по карте
            if (Application.Current.InstallState == InstallState.Installed)
            {
                Install.Visibility = Visibility.Collapsed;
            }

            _tr.ScaleX = 0.2;
            _tr.ScaleY = 0.2;
            _tr1.ScaleX = 0.2;
            _tr1.ScaleY = 0.2;

            this.MouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs e)
            {
                popup.IsOpen = false;
                duringdrag = true;               
                lastmousedownpos = e.GetPosition(rotate);
                prov1 = e.GetPosition(rotate);                
           
                    if (!isDragging)
                    {
                        isDragging = true;
                        Point point = e.GetPosition(Roads);
                    } p++;
                    
                   if (image1.Source == null) Dispatcher.BeginInvoke(() => addImage());
            };

            this.MouseMove += delegate(object sender, MouseEventArgs e)
            {                
                lastmousepos = e.GetPosition(rotate);
                if ((duringdrag) && (flagHouse) && (flagKvart))
                {
                    if (image1.Source != null)
                    {
                        layers.Visibility = Visibility.Collapsed;
                        image1.Visibility = Visibility.Visible;
                    }
                    else
                    {
                    }
                    MyTranslate.Y = -lastmousedownpos.Y + lastmousepos.Y + nach.Y;
                    MyTranslate.X = -lastmousedownpos.X + lastmousepos.X + nach.X;
                    ImageTranslate.Y = -lastmousedownpos.Y + lastmousepos.Y;
                    ImageTranslate.X = -lastmousedownpos.X + lastmousepos.X;
                }

                getInfo(e);
                
            };
            
            this.MouseLeftButtonUp += delegate(object sender, MouseButtonEventArgs e)

            {
                image1.Source = null;
                layers.Visibility = Visibility.Visible;
                image1.Visibility = Visibility.Collapsed;
                if (isDragging)
                {
                    isDragging = false;
                }

                duringdrag = false;
                nach.X = MyTranslate.X;
                nach.Y = MyTranslate.Y;
                prov2 = e.GetPosition(rotate);              
            };

            this.MouseLeave += delegate(object sender, MouseEventArgs e)
            {
                duringdrag = false;
                nach.X = MyTranslate.X;
                nach.Y = MyTranslate.Y;
            };

            this.MouseWheel += delegate(object sender, MouseWheelEventArgs e)
            {
                if (flagHouse && flagKvart)
                {
                    //double startZoom = zoom;
                    //double endZoom = 0.0;
                    //double time = 0.0;
                    if (e.Delta > 0)
                    {
                        if (zoom < 1.1)
                        {
                            zoom *= 1.5;
                        }
                        //endZoom = zoom;
                        //time = r2(Math.Abs(endZoom - startZoom) * 100);
                    }
                    else
                    {
                        if (zoom > 0.003)
                        {
                            zoom /= 1.5;
                        }
                        //endZoom = zoom;
                        //time = r2(Math.Round(Math.Abs(endZoom - startZoom) * 10);
                    }

                    zoomProcedure(zoom, e.GetPosition(translate));
                   
                    //Animation(MyScale, "ScaleTransform", "ScaleX", time, startZoom, endZoom);
                    //Animation(MyScale, "ScaleTransform", "ScaleY", time, startZoom, endZoom);    
                }
            };

            this.KeyDown += delegate(object sender, KeyEventArgs e)
            {
                if (e.Key == Key.Right)
                {
                    MyTranslate.X -= 20;
                    nach.X = MyTranslate.X;
                }
                if (e.Key == Key.Left)
                {
                    MyTranslate.X += 20;
                    nach.X = MyTranslate.X;
                }
                if (e.Key == Key.Up)
                {
                    MyTranslate.Y += 20;
                    nach.Y = MyTranslate.Y;
                }
                if (e.Key == Key.Down)
                {
                    MyTranslate.Y -= 20;
                    nach.Y = MyTranslate.Y;
                }
                if (e.Key == Key.Escape)
                {
                    FullScreen.Content = "Во весь экран";
                }
                if (e.Key == Key.PageUp|| e.Key == Key.PageDown)
                {
                    if (e.Key == Key.PageUp)
                    {
                        if (zoom < 1.1)
                            zoom *= 1.5;
                    }
                    else
                        if (zoom > 0.003)
                            zoom /= 1.5;

                    zoomProcedure(zoom, lastmousepos);
                }
            };
#endregion
        }

           

        #region ОБРАБОТЧИКИ (MainPage ЭЛЕМЕНТЫ)
        private void comments_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //HtmlPopupWindowOptions options = new HtmlPopupWindowOptions();
            //HtmlPage.PopupWindow(new Uri("http://road.perm.ru/index.php?id=636"), "article", options);
            comment.commentId = 0;
            comment.Show();
        }


//FullScreen
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Application.Current.Host.Content.IsFullScreen = !Application.Current.Host.Content.IsFullScreen;
            if (FullScreen.Content.ToString() == "Во весь экран" &&  Application.Current.Host.Content.IsFullScreen ==true)
                FullScreen.Content = "Свернуть";
            else FullScreen.Content = "Во весь экран";
        }

//Сброс ZOOM
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            zoom = nachzoom;
            double dX = 500;
            double dY = 200;

            MyScale.ScaleX = zoom;
            MyScale.ScaleY = zoom;

            MyTranslate.X = dX;
            MyTranslate.Y = dY;

            nach.X = MyTranslate.X;
            nach.Y = MyTranslate.Y;
        }

//Установка приложения
        private void Install_Click(object sender, RoutedEventArgs e)
        {
            if (Application.Current.InstallState == InstallState.NotInstalled)
            {
                Application.Current.Install();
            }
        }

        /// <summary>
        /// Добавление дороги рейтинг в функции обновления рейтинга в обработчике RoadReating_Click()
        /// </summary>
        void addRaitingRoad(Polyline road)
        {
            _LoadRoads.LoadRoadsRoad info = road.Tag as _LoadRoads.LoadRoadsRoad;
            PointCollection pc = Clone(road.Points);
            Polyline border = new Polyline();
            border.Points = pc;
            border.Name = "Rait-" + info.id.ToString();
            border.IsHitTestVisible = false;
            border.StrokeThickness = (city != "permkray") ? 32 : 32 * strokePermkray;
            border.StrokeEndLineCap = PenLineCap.Round;
            border.StrokeStartLineCap = PenLineCap.Round;
            border.StrokeLineJoin = PenLineJoin.Round;
            Colored(border, info.reit);
        }

        /// <summary>
        /// Добавление бордера для АЗС, автомоек рейтинг в функции обновления рейтинга в обработчике RoadReating_Click()
        /// </summary>
        void addRaitingGas(System.Windows.Controls.Image gas, string type)
        {
            Border border = new Border();
            border.Width = gas.ActualWidth + 10;
            border.Height = gas.ActualHeight + 10;            
            border.IsHitTestVisible = false;
            border.CornerRadius = new CornerRadius(10);

            switch (type)
            {
                case "gas":
                    {
                        _GASstation.GASstationGAS info = gas.Tag as _GASstation.GASstationGAS;
                        border.Name = "GAS-" + info.no.ToString();
                        Canvas.SetTop(border, -info.Y - border.Height / 2);
                        Canvas.SetLeft(border, info.X - border.Width / 2);
                        Colored(border, info.reit);
                        break;
                    }
                case "carwash":
                    {
                        _GASstation.GASstationGAS info = gas.Tag as _GASstation.GASstationGAS;
                        border.Name = "GAS-" + info.no.ToString();
                        Canvas.SetTop(border, -info.Y - border.Height / 2);
                        Canvas.SetLeft(border, info.X - border.Width / 2);
                        Colored(border, info.reit);
                        break;
                    }
            }
        }

//Оценка дорог
        private void RoadReating_Click(object sender, RoutedEventArgs e)
        {            
            string плохиеДороги = "";
            string хорошиеДороги = "";
            string плохиеАЗС = "";
            string хорошиеАЗС = "";
            string плохиеАвтомойки = "";
            string хорошиеАвтомойки = "";

            if (listBoxRoad1.Items.Count == 0 & listBoxRoad2.Items.Count == 0 & listBoxGAS1.Items.Count == 0 & listBoxGAS2.Items.Count == 0 & listBoxCarwash1.Items.Count == 0 & listBoxCarwash2.Items.Count == 0)
            { 
                msg.info.Text = "Ничего невыбрано";
                msg.Show();
            }
            else
            {
                for (int i = 0; i <= listBoxRoad1.Items.Count - 1; i++)
                {
                    Polyline road = (Polyline)FindName("Road-" + listBoxRoad1.Items[i].ToString() + "-r");
                    road.Name = road.Name.Substring(0, road.Name.Length - 1);
                    ((_LoadRoads.LoadRoadsRoad)road.Tag).reit -= 1;
                    Polyline road_rait = (Polyline)FindName("Rait-" + listBoxRoad1.Items[i].ToString());
                    Perm._LoadRoads.LoadRoadsRoad info = road.Tag as Perm._LoadRoads.LoadRoadsRoad;
                    road.Name = road.Name.Substring(0,road.Name.Length - 1);
                    ОкраскаПоСтатусу(road);

                    MINrait = (info.reit< MINrait) ? info.reit : MINrait;
                    TabControl tab = new TabControl();
                    fillMinMaxRaiting(tab.TabIndex);

                    if (road_rait != null)
                    {
                        Colored(road_rait, info.reit);
                    }
                    else
                    {
                        addRaitingRoad(road);
                    }

                    плохиеДороги += listBoxRoad1.Items[i];
                    if (i != listBoxRoad1.Items.Count - 1)
                    {
                        плохиеДороги += ";";
                    }
                }
                for (int i = 0; i <= listBoxRoad2.Items.Count - 1; i++)
                {
                    Polyline road = (Polyline)FindName("Road-" + listBoxRoad2.Items[i].ToString() + "-g");
                    road.Name = road.Name.Substring(0, road.Name.Length - 1);
                    ((_LoadRoads.LoadRoadsRoad)road.Tag).reit += 1;
                    Polyline road_rait = (Polyline)FindName("Rait-" + listBoxRoad2.Items[i].ToString());
                    Perm._LoadRoads.LoadRoadsRoad info = road.Tag as Perm._LoadRoads.LoadRoadsRoad;
                    ОкраскаПоСтатусу(road);

                    MAXrait = (info.reit > MAXrait) ? info.reit : MAXrait;
                    TabControl tab = new TabControl();
                    fillMinMaxRaiting(tab.TabIndex);

                    if (road_rait != null)
                    {
                        Colored(road_rait, info.reit);
                    }
                    else
                    {
                        addRaitingRoad(road);    
                    }

                    хорошиеДороги += listBoxRoad2.Items[i];
                    if (i != listBoxRoad2.Items.Count - 1)
                    {
                        хорошиеДороги += ";";
                    }
                }
                for (int i = 0; i <= listBoxGAS1.Items.Count - 1; i++)
                {
                    System.Windows.Controls.Image gas = (System.Windows.Controls.Image)FindName("GAS-image-" + listBoxGAS1.Items[i].ToString() + "-r");
                    gas.Name = gas.Name.Substring(0, gas.Name.Length - 1);
                    ((_GASstation.GASstationGAS)gas.Tag).reit -= 1;
                    Border b = (Border)FindName("GAS-" + listBoxGAS1.Items[i].ToString());
                    Perm._GASstation.GASstationGAS info = gas.Tag as Perm._GASstation.GASstationGAS;
                    ОкраскаПоСтатусу(gas);

                    MINraitGAS = (info.reit < MINraitGAS) ? info.reit : MINraitGAS;
                    TabControl tab = new TabControl();
                    fillMinMaxRaiting(tab.TabIndex);

                    if (b!=null)
                    {
                        Colored(b, info.reit);
                    }
                    else
                    {
                        addRaitingGas(gas, "gas");                       
                    }

                    плохиеАЗС += listBoxGAS1.Items[i];
                    if (i != listBoxGAS1.Items.Count - 1)
                    {
                        плохиеАЗС += ";";
                    }
                }
                for (int i = 0; i <= listBoxGAS2.Items.Count - 1; i++)
                {
                    System.Windows.Controls.Image gas = (System.Windows.Controls.Image)FindName("GAS-image-" + listBoxGAS2.Items[i].ToString()+"-g");
                    gas.Name = gas.Name.Substring(0, gas.Name.Length - 1);
                    ((_GASstation.GASstationGAS)gas.Tag).reit += 1;
                    Border b = (Border)FindName("GAS-"+listBoxGAS2.Items[i].ToString());
                    Perm._GASstation.GASstationGAS info = gas.Tag as Perm._GASstation.GASstationGAS;
                    ОкраскаПоСтатусу(gas);

                    MAXraitGAS = (info.reit > MAXraitGAS) ? info.reit : MAXraitGAS;
                    TabControl tab = new TabControl();
                    fillMinMaxRaiting(tab.TabIndex);

                    if (b != null)
                    {
                        Colored(b, info.reit);
                    }
                    else
                    {
                        addRaitingGas(gas, "gas");
                    }

                    хорошиеАЗС += listBoxGAS2.Items[i];
                    if (i != listBoxGAS2.Items.Count - 1)
                    {
                        хорошиеАЗС += ";";
                    }
                }
                for (int i = 0; i <= listBoxCarwash1.Items.Count - 1; i++)
                {
                    System.Windows.Controls.Image carwash = (System.Windows.Controls.Image)FindName("Carwash-image-" + listBoxCarwash1.Items[i].ToString() + "-r");
                    carwash.Name = carwash.Name.Substring(0, carwash.Name.Length - 1);
                    ((_CarWash.CarWashCarwash)carwash.Tag).reit -= 1;
                    Border b = (Border)FindName("Carwash-" + listBoxCarwash1.Items[i].ToString());
                    Perm._CarWash.CarWashCarwash info = carwash.Tag as Perm._CarWash.CarWashCarwash;
                    ОкраскаПоСтатусу(carwash);

                    MINraitCarwash = (info.reit < MINraitCarwash) ? info.reit : MINraitCarwash;
                    TabControl tab = new TabControl();
                    fillMinMaxRaiting(tab.TabIndex);

                    if (b != null)
                    {
                        Colored(b, info.reit);
                    }
                    else
                    {
                        addRaitingGas(carwash, "carwash");
                    }

                    плохиеАвтомойки += listBoxCarwash1.Items[i];
                    if (i != listBoxCarwash1.Items.Count - 1)
                    {
                        плохиеАвтомойки += ";";
                    }
                }
                for (int i = 0; i <= listBoxCarwash2.Items.Count - 1; i++)
                {
                    System.Windows.Controls.Image carwash = (System.Windows.Controls.Image)FindName("Carwash-image-" + listBoxCarwash2.Items[i].ToString() + "-g");
                    carwash.Name = carwash.Name.Substring(0, carwash.Name.Length - 1);
                    ((_CarWash.CarWashCarwash)carwash.Tag).reit += 1;
                    Border b = (Border)FindName("Carwash-" + listBoxCarwash2.Items[i].ToString());
                    Perm._CarWash.CarWashCarwash info = carwash.Tag as Perm._CarWash.CarWashCarwash;
                    ОкраскаПоСтатусу(carwash);

                    MAXraitCarwash = (info.reit > MAXraitCarwash) ? info.reit : MAXraitCarwash;
                    TabControl tab = new TabControl();
                    fillMinMaxRaiting(tab.TabIndex);

                    if (b != null)
                    {
                        Colored(b, info.reit);
                    }
                    else
                    {
                        addRaitingGas(carwash, "carwash");
                    }

                    хорошиеАвтомойки += listBoxCarwash2.Items[i];
                    if (i != listBoxCarwash2.Items.Count - 1)
                    {
                        хорошиеАвтомойки += ";";
                    }
                }
                int addVote = listBoxRoad1.Items.Count + listBoxRoad2.Items.Count + listBoxGAS1.Items.Count + listBoxGAS2.Items.Count + listBoxCarwash1.Items.Count + listBoxCarwash2.Items.Count;
                currentVote += addVote;
                if (VOTE.Text != currentVote.ToString())
                {
                    VOTE.Text = currentVote.ToString();
                    VOTE2.Text = currentVote.ToString();
                    VOTE3.Text = currentVote.ToString();
                }
                if (CONFIG_SAVE_RATING) ЗаписьРейтинга(плохиеДороги, хорошиеДороги, плохиеАЗС, хорошиеАЗС, плохиеАвтомойки, хорошиеАвтомойки);
                if (city == "perm" && CONFIG_SAVE_BANNER) CreateJPG();
            }
        }

        void CreateJPG ()
        {
            borderBanner.Opacity = 1;
            banner.UpdateLayout();

            wb = new WriteableBitmap((int)borderBanner.ActualWidth, (int)borderBanner.ActualHeight);
            wb.Render(banner, new MatrixTransform());
            wb.Invalidate();
            try
            {
                IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForSite();
                using (FileStream stream = store.CreateFile("get.png"))
                {
                    IImageEncoder encoder = new PngEncoder();
                    var image = wb.ToImage();
                    encoder.Encode(image, stream);
                }
                using (FileStream isfs = store.OpenFile("get.png", FileMode.Open))
                {
                    byte[] retVal = new byte[isfs.Length];
                    isfs.Read(retVal, 0, retVal.Length);
                    _Banner.BannerClient proxyBanner = new _Banner.BannerClient();
                    proxyBanner.DoWorkCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxyBanner_DoWorkCompleted);
                    proxyBanner.DoWorkAsync(retVal);
                    proxyBanner.CloseAsync();
                }
                store.DeleteFile("get.png");
            }
            catch { }   
            borderBanner.Opacity = 0;
        }
        
        void proxyBanner_DoWorkCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {            
        }

//сброс рейтинга
        private void Reset_Click(object sender, RoutedEventArgs e)
        {
            ResetReiting();
        }
//Обработчики лампочек---------------------
        private void green_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (good.IsChecked == true)
            {
                good.IsChecked = false;
                bad.IsChecked = true;
                green.Source = new BitmapImage(new Uri("../Images/0.png", UriKind.RelativeOrAbsolute));
                red.Source = new BitmapImage(new Uri("../Images/11.png", UriKind.RelativeOrAbsolute));
            }
            else
            {
                good.IsChecked = true;
                bad.IsChecked = false;
                green.Source = new BitmapImage(new Uri("../Images/00.png", UriKind.RelativeOrAbsolute));
                red.Source = new BitmapImage(new Uri("../Images/1.png", UriKind.RelativeOrAbsolute));
            }
        }

        private void red_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (bad.IsChecked == true)
            {
                good.IsChecked = true;
                bad.IsChecked = false;
                green.Source = new BitmapImage(new Uri("../Images/00.png", UriKind.RelativeOrAbsolute));
                red.Source = new BitmapImage(new Uri("../Images/1.png", UriKind.RelativeOrAbsolute));
            }
            else
            {
                good.IsChecked = false;
                bad.IsChecked = true;
                green.Source = new BitmapImage(new Uri("../Images/0.png", UriKind.RelativeOrAbsolute));
                red.Source = new BitmapImage(new Uri("../Images/11.png", UriKind.RelativeOrAbsolute));
            }
        }

        private void green_MouseEnter(object sender, MouseEventArgs e)
        {
            green.Source = new BitmapImage(new Uri("../Images/00.png", UriKind.RelativeOrAbsolute));
            green.MouseLeave += new MouseEventHandler(green_MouseLeave);
        }

        void green_MouseLeave(object sender, MouseEventArgs e)
        {
            if (good.IsChecked != true)
            {
                green.Source = new BitmapImage(new Uri("../Images/0.png", UriKind.RelativeOrAbsolute));
            }
        }

        private void red_MouseEnter(object sender, MouseEventArgs e)
        {
            red.Source = new BitmapImage(new Uri("../Images/11.png", UriKind.RelativeOrAbsolute));
            red.MouseLeave += new MouseEventHandler(red_MouseLeave);
        }

        void red_MouseLeave(object sender, MouseEventArgs e)
        {
            if (bad.IsChecked != true)
            {
                red.Source = new BitmapImage(new Uri("../Images/1.png", UriKind.RelativeOrAbsolute));
            }
        }
        
        private void bad_Click(object sender, RoutedEventArgs e)
        {
            green.Source = new BitmapImage(new Uri("../Images/0.png", UriKind.RelativeOrAbsolute));
            red.Source = new BitmapImage(new Uri("../Images/11.png", UriKind.RelativeOrAbsolute));
        }

        private void good_Click(object sender, RoutedEventArgs e)
        {
            green.Source = new BitmapImage(new Uri("../Images/00.png", UriKind.RelativeOrAbsolute));
            red.Source = new BitmapImage(new Uri("../Images/1.png", UriKind.RelativeOrAbsolute));
        }

//Нажатие кнопки продожить
        private void Continue_Click(object sender, RoutedEventArgs e)
        {
            gridIntro.Visibility = Visibility.Collapsed;
            Loader.Visibility = Visibility.Collapsed;
            main.Visibility = Visibility.Visible;
            Continue.Visibility = Visibility.Collapsed;
        }
//--------------------------------------------
//Закрытие popUp меню
        private void popupGrid_MouseLeave(object sender, MouseEventArgs e)
        {
            Animation(popupGrid, "Grid", "BlurEffect", 0.5, 0, 30);
            popup.IsOpen = false;
        }

        #endregion
        #region СЛОИ ON/OFF
        private void ReitingVisible_Click(object sender, RoutedEventArgs e)
        {
            if (Raiting.Visibility == Visibility.Visible)
            {
                Raiting.Visibility = Visibility.Collapsed;
            }
            else
            {
                Raiting.Visibility = Visibility.Visible;
            }
        }

        private void ReitingVisible_1_Click(object sender, RoutedEventArgs e)
        {
            if (Raiting_1.Visibility == Visibility.Visible)
            {
                Raiting_1.Visibility = Visibility.Collapsed;
            }
            else
            {
                Raiting_1.Visibility = Visibility.Visible;
            }
        }

        private void ReitingVisible_2_Click(object sender, RoutedEventArgs e)
        {
            if (Raiting_2.Visibility == Visibility.Visible)
            {
                Raiting_2.Visibility = Visibility.Collapsed;
            }
            else
            {
                Raiting_2.Visibility = Visibility.Visible;
            }
        }

        private void ReitingVisible_3_Click(object sender, RoutedEventArgs e)
        {
            if (Raiting_3.Visibility == Visibility.Visible)
            {
                Raiting_3.Visibility = Visibility.Collapsed;
            }
            else
            {
                Raiting_3.Visibility = Visibility.Visible;
            }
        }

        private void ReitingVisible_4_Click(object sender, RoutedEventArgs e)
        {
            if (Raiting_4.Visibility == Visibility.Visible)
            {
                Raiting_4.Visibility = Visibility.Collapsed;
            }
            else
            {
                Raiting_4.Visibility = Visibility.Visible;
            }
        }

        private void ReitingVisible_5_Click(object sender, RoutedEventArgs e)
        {
            if (Raiting_5.Visibility == Visibility.Visible)
            {
                Raiting_5.Visibility = Visibility.Collapsed;
            }
            else
            {
                Raiting_5.Visibility = Visibility.Visible;
            }
        }

        private void ReitingVisible_6_Click(object sender, RoutedEventArgs e)
        {
            if (Raiting_6.Visibility == Visibility.Visible)
            {
                Raiting_6.Visibility = Visibility.Collapsed;
            }
            else
            {
                Raiting_6.Visibility = Visibility.Visible;
            }
        }

        private void RoadVisible_Click(object sender, RoutedEventArgs e)
        {
            if (Roads.Visibility == Visibility.Visible)
            {
                Roads.Visibility = Visibility.Collapsed;
            }
            else
            {
                Roads.Visibility = Visibility.Visible;
            }
        }

        private void StreetVisible_Click(object sender, RoutedEventArgs e)
        {
            if (Streets.Visibility == Visibility.Visible)
            {
                Streets.Visibility = Visibility.Collapsed;
            }
            else
            {
                Streets.Visibility = Visibility.Visible;
            }
        }

        private void HouseVisible_Click(object sender, RoutedEventArgs e)
        {
            if (House.Visibility == Visibility.Collapsed)
            {
                if (LH == false)
                {
                    Loader.Visibility = Visibility.Visible;
                    main.Visibility = Visibility.Collapsed;
                    LoadHouse();
                    LH = true;
                }

                House.Visibility = Visibility.Visible;
            }
            else
            {
                House.Visibility = Visibility.Collapsed;
            }
        }

        private void MapVisible_Click(object sender, RoutedEventArgs e)
        {
            if (Map.Visibility == Visibility.Collapsed)
            {
                if (LL == false)
                {
                    Loader.Visibility = Visibility.Visible;
                    main.Visibility = Visibility.Collapsed;
                    loadLandscape();
                    LL = true;
                }

                Map.Visibility = Visibility.Visible;
            }
            else
            {
                Map.Visibility = Visibility.Collapsed;
            }
        }
        private void GASVisible_Click(object sender, RoutedEventArgs e)
        {
            if (Station.Visibility == Visibility.Visible)
            {
                Station.Visibility = Visibility.Collapsed;
            }
            else
            {
                Station.Visibility = Visibility.Visible;
            }
        }

        

        private void CarwashVisible_Click(object sender, RoutedEventArgs e)
        {
            if (canvasCarwash.Visibility == Visibility.Visible)
            {
                canvasCarwash.Visibility = Visibility.Collapsed;
            }
            else
            {
                canvasCarwash.Visibility = Visibility.Visible;
            }
        }

        private void ReitingCarwashVisible_Click(object sender, RoutedEventArgs e)
        {
            if (CarwashRaiting.Visibility == Visibility.Visible)
            {
                CarwashRaiting.Visibility = Visibility.Collapsed;
            }
            else
            {
                CarwashRaiting.Visibility = Visibility.Visible;
            }
        }

        
        #endregion        

        private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (tabControl1 != null)
            {
                fillMinMaxRaiting(tabControl1.SelectedIndex);
            }
        }
    }
}


